#! /bin/zsh

LINK_EIGO="$1"
LINK_NIHONGO="$2"
COOKIE_JAR="$3"
USER_AGENT="Mozilla/5.0 (X11; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0"

function died {
	echo "╋╋╋ Died during $@ ╋╋╋"
	exit 2
}

if [[ "${LINK_EIGO::8}" != "https://" ]]; then
	echo "The eigo link is no good."
	exit 1
fi

if [[ "${LINK_NIHONGO::8}" != "https://" ]]; then
	echo "The nihongo link is no good."
	exit 1
fi

if [[ ! -a "${COOKIE_JAR}" ]]; then
	echo "The cookie jar is no good."
	exit 1
fi

PREFIX="tmp$RANDOM"

yt-dlp --cookies "${COOKIE_JAR}" --user-agent "${USER_AGENT}" --write-info-json --output "${PREFIX}" --skip-download "${LINK_NIHONGO}" || died while downloading info JSON
yt-dlp --cookies "${COOKIE_JAR}" --user-agent "${USER_AGENT}" --remux-video mkv "${LINK_EIGO}" --output "${PREFIX}-en.mkv" || died while downloading en
yt-dlp --cookies "${COOKIE_JAR}" --user-agent "${USER_AGENT}" --sub-langs en-US --embed-subs --format "best[height=720]" --remux-video mkv "${LINK_NIHONGO}" --output "${PREFIX}-jp.mkv" || died while downloading jp

TITLE="$(jq --raw-output .title < ${PREFIX}.info.json)" || died while parsing info JSON

#mkvmerge -o "${TITLE}.mkv" --language 0:eng --language 1:eng --no-subtitles "${PREFIX}-en.mkv" --language 1:jpn --language 2:eng --no-video "${PREFIX}-jp.mkv" || died while mkvmerging
echo "mkvmerge -o \"${TITLE}.mkv\" --language 0:eng --language 1:eng --no-subtitles ${PREFIX}-en.mkv --language 1:jpn --language 2:eng --no-video ${PREFIX}-jp.mkv" >> merge.sh

#rm "${PREFIX}-en.mkv" "${PREFIX}-jp.mkv" "${PREFIX}.info.json" || died while removing temporary files
