#!/bin/bash
# Rick Astley in your Terminal.
# By Serene Han and Justine Tunney <3

# or curl -sL https://bit.ly/3oZZ0OG | bash

version='1.1'
rick='https://konsthol.eu'
video="$rick/astley80.full.bz2"
audio_raw="$rick/roll.s16"
audpid=0
purp='\x1b[38;5;171m'
echo -en '\x1b[s'  # Save cursor.

cleanup() { (( audpid > 1 )) && kill $audpid 2>/dev/null; }
quit() { echo -e "\x1b[2J \x1b[0H ${purp}Rick Rolled <3 \x1b[?25h \x1b[u \x1b[m"; }

trap "cleanup" INT
trap "quit" EXIT

echo -en "\x1b[?25l \x1b[2J \x1b[H"  # Hide cursor, clear screen.

# On Linux, if |aplay| available, stream raw sound.
curl -s $audio_raw | aplay -Dplug:default -q -f S16_LE -r 8000 &
audpid=$!

# Sync FPS to reality as best as possible. Mac's freebsd version of date cannot
# has nanoseconds so inject python. :/

play () {

PYCMD=$(cat <<EOF
import sys
import time
fps = 25; time_per_frame = 1.0 / fps
buf = ''; frame = 0; next_frame = 0
begin = time.time()
try:
	for i, line in enumerate(sys.stdin):
		if i % 32 == 0:
			frame += 1
			sys.stdout.write(buf); buf = ''
			elapsed = time.time() - begin
			repose = (frame * time_per_frame) - elapsed
			if repose > 0.0:
				time.sleep(repose)
			next_frame = elapsed / time_per_frame
		if frame >= next_frame:
			buf += line
except KeyboardInterrupt:
	pass
EOF
)

python3 -c "$PYCMD"

}

play < <(curl -s $video | bunzip2 -q)
