#!/bin/bash
set -e

[ $# -eq 4 ] || {
	echo "need 4 arguments:"
	echo "  1) directory with subtitled mkv files"
	echo "  2) directory with audio/video mkv files"
	echo "  3) regex pattern of subtitled filenames"
	echo "  4) regex pattern of audio/video filenames"
	exit 1
}

subdir="$1"
hqdir="$2"
submask="$3"
hqmask="$4"

td="$(mktemp -d sushify.XXXXXXXXXX -t)"
odir="$(pwd)"

getfiles() {
	cd "$1"
	find -maxdepth 1 -type f |
	cut -c3- |
	grep -E "$2" |
	sort
}

getfiles "$subdir" "$submask" > "$td/fa"
getfiles "$hqdir" "$hqmask" > "$td/fb"

echo
paste "$td/"{fa,fb}
printf '\npress enter to continue or ctrl-c to bail\n'
read -u1 -r

command -v deactivate >/dev/null &&
	printf '\033[33mdeactivating foreign virtualenv\033[0m\n' &&
	deactivate

. ~/pe/ve.sushi/bin/activate || {
	printf '\033[33msushi env not found; preparing...\033[0m\n'
	mkdir -p ~/pe
	python3 -m venv ~/pe/ve.sushi
	. ~/pe/ve.sushi/bin/activate
	pip install numpy
	ln -s /usr/bin/scxvid ~/pe/ve.sushi/bin/SCXvid
}

[ -e ~/pe/sushi/sushi.py ] || {
	printf '\033[33msushi not found; installing...\033[0m\n'
	cd ~/pe
	git clone https://github.com/tp7/sushi
}

paste -d'\t' "$td"/f{a,b} |
while IFS=$'\t' read f1 f2
do
	~/pe/sushi/sushi.py \
		--src "$subdir/$f1" \
		--dst "$hqdir/$f2" \
		--temp-dir "$td" \
		</dev/null
	#	--src-keyframes make \
	#	--dst-keyframes make 
done
