#!/bin/sh

depend() {
	pactree -u -d 1 "$1" | tail -n +2 | sort
}

emacs() {
	# Create new frame (if there isnt one or no file is specified)
	if [ -z "$(pgrep -f emacsclient.*-c)" ] || [ "$1" = "" ]; then
		setsid -f emacsclient -a '' -c "$@" > /dev/null 2>&1
	else
		setsid -f emacsclient -a '' "$@" > /dev/null 2>&1
	fi
}

# $1 = find, $2 = list, $3 = list separator
in_list() {
	[ -z "$1" ] || [ -z "$2" ] && return 1
	if ! echo "$2" | awk -v m="^$1$" -v RS="${3:-' '}" '$0 ~ m { exit 1 }'; then
		return 0
	else
		return 1
	fi
}

java_doc() {
	mkdir -p './doc';
	javadoc -d './doc' -- *.java
}

java_run () {
	mkdir -p './out';
	javac -d './out' "$1.java";
	java -cp './out' "$1"
}

# Search for packages, by name only
pacman_search() {
	pacman -Ss "$1" --color=always | \
		awk -v m="$1" '{ if ($0 !~ /^\s/) { if ($1 ~ m) { print; }} else { print; }}'
}

pastebin() {
	echo "$1" | curl -F 'f:1=<-' ix.io
}

print_project() {
	tree -f --noreport | egrep -ve "vendor(\/.*){2}" -ve "build(\/.*)" | sed -E 's%\./.*/%%g; s%\./%%g;'
}

raspbian() {
	sudo systemctl start avahi-daemon.service
	if ! ip a show usb0 | grep -q 'inet6'; then
		sudo dhcpcd usb0
	fi
	ssh -6 pi@"$(avahi-resolve-host-name raspberrypi.local | awk '{ print $2 }')"%usb0
	sudo systemctl stop avahi-daemon.service
}

screencast() {
	IS_RUNNING="$(pgrep ffmpeg)"
	if [ "$IS_RUNNING" != "" ]; then
		notify-send "Stopped recording.."
		# Kill with SIGTERM, allowing finishing touches
		pkill -15 ffmpeg
		sleep 3
		# Kill with SIGKILL, just in case it is still running
		pkill -9 ffmpeg
	else
		width=1280
		height=720
		NAME=${1:-"$CAPTURE/$(date '+%Y-%m-%d-%H%M%S')_${width}x${height}_ffmpeg"}

		[ -n "$2" ] && AUDIO_CODEC="-c:a aac"
		[ -n "$2" ] && AUDIO_SOURCE="-f pulse -ac 2 -i $2" # 1 = system, 2 = mic

		notify-send "Started recording.."
		ffmpeg -y \
			-threads 8 \
			-f x11grab \
			-framerate 30 \
			-s "${width}x${height}" \
			-i "$DISPLAY.0+640,180" \
			$AUDIO_SOURCE \
			-r 30 \
			$AUDIO_CODEC \
			-c:v libx264 -crf 0 -preset ultrafast \
			"$NAME.mkv" &
	fi
}

sha384sum() {
	tmpfile=$(mktemp)
	curl -o "$tmpfile" "$1" && openssl dgst -sha384 -binary "$tmpfile" | openssl base64 -A
	rm -f "$tmpfile"
}

shuffle() {
	echo "$1" | fold -w 1 | shuf | tr -d '\n'
}

stream() {
	channel="$1"
	quality=${2:-"best"}
	lowLatency="$3"

	if [ "$quality" = "list" ]; then
		streamlink "https://twitch.tv/$1" --config "/dev/null"
	elif [ "$quality" != "low" ] && [ -z "$lowLatency" ]; then
		echo "Starting stream https://twitch.tv/$channel at quality: $quality"
		setsid -f streamlink \
			   --player mpv \
			   --stream-sorting-excludes "<480p,>=1080p" \
			   "https://twitch.tv/$channel" "$quality" > /dev/null 2>&1 &
	else
		[ "$quality" = "low" ] && quality="best"
		echo "Starting stream https://twitch.tv/$channel at quality: $quality"
		setsid -f streamlink \
			   --twitch-low-latency \
			   --player mpv \
			   --player-args '--cache=yes --demuxer-max-bytes=750k' \
			   --stream-sorting-excludes "<480p,>=1080p" \
			   "https://twitch.tv/$channel" "$quality" > /dev/null 2>&1 &
	fi
}

update_mirrorlist() {
	sudo rm /etc/pacman.d/mirrorlist.pacnew
	sudo reflector --latest 100 --protocol https --sort rate --save /etc/pacman.d/mirrorlist
}

webmconvert() {
	[ "$2" = "1" ] && AUDIO="-c:a libvorbis" || AUDIO="-an"

	# https://trac.ffmpeg.org/wiki/Encode/H.264
	# https://trac.ffmpeg.org/wiki/Encode/VP8
	# -qmin 0   (0-63, default 4, lower = better quality)
	# -qmax 40  (qmin-63, default 63)
	# -crf 16   (0-51, default 23, 0 = lossless)
	# -b:v 4M
	ffmpeg -threads 4 -i "$1" -c:v libvpx -qmin 0 -qmax 40 -crf 16 -b:v 4M "$AUDIO" "${1%.*}_convert.webm"
}

ytaudio_thumbnail() {
	# Get file name
	echo "Retrieving video name.."
	FILE_NAME="$(youtube-dl --get-filename "$1")"
	FILE_NAME="${FILE_NAME%.*}"

	# Get mp3 + thumbnail
	echo "Downloading and converting \"$FILE_NAME\".."
	youtube-dl -f bestaudio/best -x --audio-format mp3 --audio-quality 0 \
			   --write-thumbnail --external-downloader aria2c \
			   --cookies "$HOME/documents/youtube.com-cookies.txt" "$1" > /dev/null

	echo "Embedding thumbnail into mp3.."

	# Convert thumbnail to actually be a jpg
	yes y | ffmpeg -i "${FILE_NAME}.webp" "${FILE_NAME}_converted.jpg" > /dev/null 2>&1
	yes y | ffmpeg -i "${FILE_NAME}.jpg" "${FILE_NAME}_converted.jpg" > /dev/null 2>&1

	# Embed thumbnail into mp3
	yes y | ffmpeg -i "${FILE_NAME}.mp3" -i "${FILE_NAME}_converted.jpg" \
				  -map 0:0 -map 1:0 -c copy -id3v2_version 3 \
				  -metadata:s:v title="Album cover" \
				  -metadata:s:v comment="Cover (front)" \
				  "${FILE_NAME}_embed.mp3" > /dev/null 2>&1

	# Remove left over files
	rm -f "./${FILE_NAME}_converted.jpg" "./${FILE_NAME}.jpg" "./${FILE_NAME}.mp3"
	mv "${FILE_NAME}_embed.mp3" "${FILE_NAME}.mp3"
}

"$@"