#!/bin/bash
pythonexec='/usr/bin/python3'
pkgdatadir='/usr/share/varia'

aria2cexec=$pkgdatadir/../../bin/aria2-next
ffmpegexec=$pkgdatadir/../../bin/ffmpeg
sevenzexec=$pkgdatadir/../../bin/7zz
jsruntimeexec=$pkgdatadir/../../bin/qjs
jsruntime='quickjs'
jsruntimeexecname='qjs'

while [ $# -gt 0 ] ; do
  case $1 in
	-h|--help) echo "Options:
	--aria2cexec PATH		Path to aria2c executable
	--ffmpegexec PATH		Path to ffmpeg executable
	--sevenzexec PATH		Path to 7z executable
	--jsruntime NAME		JavaScript runtime name (read by yt-dlp, defaults to quickjs)
	--jsruntimeexec PATH	Path to JS runtime executable
	-h, --help				Show this help message"
	exit 0 ;;
	--aria2cexec) aria2cexec="$2"; shift ;;
	--ffmpegexec) ffmpegexec="$2"; shift ;;
	--sevenzexec) sevenzexec="$2"; shift ;;
    --jsruntime) jsruntime="$2"; shift ;;
	--jsruntimeexec) jsruntimeexec="$2"; shift ;;
	*) break ;;
  esac
  shift
done

if !(test -f $aria2cexec;)
then
	aria2cexec=$(which aria2-next)
	if !(test -f $aria2cexec;)
	then
		aria2cexec=$(which aria2c)
		if !(test -f $aria2cexec;)
		then
			echo "Error: aria2-next or aria2c not found."
		fi
	fi
fi

if !(test -f $ffmpegexec;)
then
	ffmpegexec=$(which ffmpeg)
	if !(test -f $ffmpegexec;)
	then
		echo "Error: ffmpeg not found."
	fi
fi

if !(test -f $sevenzexec;)
then
	sevenzexec=$(which 7z)
	if !(test -f $sevenzexec;)
	then
		echo "Error: 7z not found."
	fi
fi

if !(test -f $jsruntimeexec;)
then
	jsruntimeexec=$(which $jsruntimeexecname)
	if !(test -f $jsruntimeexec;)
	then
		echo "Error: JS runtime (defaults to QuickJS) not found."
	fi
fi

echo "Selected JS Runtime name: ${jsruntime}"

if [ -z "$SNAP" ];
then
	$pythonexec $pkgdatadir/../../bin/varia-py.py "$aria2cexec" "$ffmpegexec" "$sevenzexec" "$jsruntime" "$jsruntimeexec" "NOSNAP" "$@"
else
	python3 $SNAP/usr/bin/varia-py.py "$aria2cexec" "$ffmpegexec" "$sevenzexec" "$jsruntime" "$jsruntimeexec" "$SNAP" "$@"
fi
