#!/bin/bash
## script to fetch and build a module of yt-dlp
## by ncmprhnsbl @ forum.porteus.org
## version 20201126

. /usr/share/porteus/porteus-functions
get_colors

# Check for root
if [ $(whoami) != "root" ]; then
	echo "Only root can run this."
	exit 1
fi

# functions set work directory(default is /tmp) to current work directory
set_tmp() {
WRKDIR=/tmp 
}

set_pwd() {
WRKDIR=$(pwd) 
}
set_tmp
# set up fakeroot and set some variables

# echo usage
show_help() {
	echo " options:  -d : do operations in the present directory, instead of /tmp . "
	echo "           -h        : show this usage. "
}
while getopts ":-d:-h:" o; do
case "$1" in
 
    -d)
       set_pwd;;
    
    -h)
      show_help
      exit 0;;
              
     *)
      show_help
      exit 1;;
    
esac
done
case "$1" in
      
    "")
      set_tmp;;
      
esac

PKG=yt-dlp
[ ! -d $WRKDIR/$PKG/usr/bin ] && mkdir -p $WRKDIR/$PKG/usr/bin
#[ ! -d $WRKDIR/$PKG/install ] && mkdir -p $WRKDIR/$PKG/install
BUILD=$WRKDIR/$PKG
BIND=$BUILD/usr/bin

checksum () {
if [ -z $CHOICE ]; then	
    echo "Verifying download integrity.."
    echo "Server  : $SUM1"
    echo "Download: $SUM2"
    if [ "$SUM1" = "$SUM2" ]; then 
         echo "Download verified." 
    else 
         echo "Integrity check failed."
         cleanup 
    fi
fi
}

# tidy up after
cleanup(){
echo
[ -d $BUILD ] && rm -rf $BUILD
[ -f $WRKDIR/SHA2-256SUMS ] && rm $WRKDIR/SHA2-256SUMS
[ -f $WRKDIR/deno*.zip ] && rm $WRKDIR/deno*.zip
[ -f $WRKDIR/quickjs*.zip ] && rm $WRKDIR/quickjs*.zip
exit	
}
trap cleanup SIGHUP SIGINT SIGTERM

# tell us where the work will be done
echo "Work will be done in: $txtgreen$WRKDIR$rst "
echo

case `uname -m` in
	x86_64)
	ARCH=x86_64
	SUFFIX=64
	SARCH=x86_64
	;;
	*)
	ARCH=i686
	SUFFIX=
	SARCH=i586
	;;
esac

#get version info
SERVER=`awk -F= '/SERVER=/{print$NF}' /etc/porteus.conf`
VURL=https://github.com/yt-dlp/yt-dlp
VER=$(lynx --dump --nonumbers https://github.com/yt-dlp/yt-dlp | grep "releases/tag" | awk -F"/" '{print$NF}')
# download URL
URL=$VURL/releases/download/$VER/yt-dlp
TAG=ncm
REV=1
JURL1="https://github.com/denoland/deno/"
JVER1=$(lynx --dump --nonumbers $JURL1 | grep "releases/tag" | awk -F"/" '{print$NF}')
JDURL1="${JURL1}releases/download/$JVER1/deno-x86_64-unknown-linux-gnu.zip"
JURL2="https://bellard.org/quickjs/binary_releases/"
JVER2=$(lynx --dump --nonumbers $JURL2 | grep linux-x86_64 | tail -n1 | awk -F/ '{print$NF}')
JDURL2="$JURL2/$JVER2"

array_menu(){
echo "$1"
echo "$2" 
select CHOICE in ${RESULT[@]}; do
    if [ -z "$CHOICE" ]; then
        red "? java interpreter chosen." && echo
			else
		echo "$txtgreen${CHOICE^^}$rst Java runtime chosen"
		echo
    fi
    break
done
}

get_js_interpreter(){
array_menu "Please choose a Javascript runtime from the menu:" 
case $CHOICE in
	deno) JDURL="$JDURL1" JS_INT="deno-x86_64-unknown-linux-gnu.zip" ;;
	quickjs) JDURL="$JDURL2" JS_INT="$JVER2" ;;
	none) JDURL="none" ;;
	*)
	echo "Invalid choice"
	$FUNCNAME
	;;
esac
}

# check for installed version
if [ $(which $PKG 2>/dev/null) ]; then
	IVER=$($PKG --version)
	echo "you have version $IVER installed"
else
	echo "$PKG is not installed"
fi

# check installed version is up to date, if so offer escape.
if [ "$VER" = "$IVER" ]; then
	read -p " You already have the latest version $txtgreen$CVER$rst. Do you still want to continue? [y/n]" -n 1 -r -s && echo
	[[ $REPLY =~ ^[Nn]$ ]] && cleanup
fi

# Get version on porteus server
SERVER_LATFILE=`lynx -dump --nonumbers --listonly $SERVER/$SARCH/current/modules | awk -F/ '/yt-dlp/{print$NF}' | tail -n1`
SERVER_LATVER=`awk -F- '{print$3}' <<<"${SERVER_LATFILE}"`
echo "Checking $SERVER/$SARCH/current/modules"

# show all version information
echo "The Porteus$txtgreen SERVER$rst version is :" $txtgreen "$SERVER_LATVER" $rst
echo
echo "The latest $PKG version is    :" $txtgreen "$VER" $rst
echo
cyan "To download from Youtube may now require a javascript runtime."
cyan "(the 1000 other supported sites do not)"
cyan "The choices we offer are : deno (large 44mb but auto detected by yt-dlp)"
cyan "or : quickjs (small 1mb but requires '--js-runtimes quickjs') "
echo
cyan "You can choose to download the premade module from our server,"
cyan "which includes quickjs." 
cyan "or download the version from github and choose a javascript runtime."  
echo

read -p " Would you like to download the porteus server version? [y/n]" -n 1 -r -s && echo  
if [[ $REPLY =~ ^[Yy]$ ]]; then
	echo
	download $SERVER/$SARCH/current/modules/$SERVER_LATFILE $WRKDIR
        ## Check that we have a module in $WRKDIR
        if [ ! -f $WRKDIR/$SERVER_LATFILE ]; then
	     	echo
	     	sayerror "Download of the $PKG module failed."
	     	echo
	     	cleanup
        else
	    	echo
	    	echo "Your file is at:" $txtcyan "$WRKDIR/$SERVER_LATFILE" $rst
	    	echo "Please move it to your modules folder to survive a reboot."
	    	echo
	    	cleanup
		fi
fi

read -p " Would you like to download $txtgreen $PKG-$VER $rst ? [y/n]"  -n 1 -r -s && echo  
if [[ ! $REPLY =~ ^[Yy]$ ]]; then 
cleanup
fi

RESULT+=( 'deno' 'quickjs' 'none' )
get_js_interpreter

# download the latest version
download $URL $BIND

# download deno or quickjs and extract to $BIND
if [[ $JDURL != "none" ]]; then
	#echo "java url is: $JDURL"
	[ ! -f $WRKDIR/$JS_INT ] && download $JDURL $WRKDIR
	unzip $WRKDIR/$JS_INT -d $BIND/
fi

## Check that we have a binary in BIND
if [ ! -f $BIND/$PKG ]; then
	echo
	sayerror "File $BIND/$PKG not found. Some went wrong with the download."
	cleanup
fi

## Check integrity of downloaded tarball using sha256sum
download $VURL/releases/download/$VER/SHA2-256SUMS $WRKDIR
SUM1=$(cat $WRKDIR/SHA2-256SUMS | head -n1 | cut -d" " -f1)
SUM2=$(sha256sum $BIND/$PKG | cut -d" " -f1)
checksum

# make executable
chmod +x $BIND/$PKG

cd $BUILD
### fake slackware type package info: super dumb version
PKGINFO=var/lib/pkgtools/packages
#FILES=`find *`
mkdir -p $PKGINFO
echo "PACKAGE NAME: $PKG-$VER-noarch-$REV$TAG" > $PKGINFO/$PKG-$VER-noarch-$REV$TAG

# add slack-desc
cat >> $PKGINFO/$PKG-$VER-noarch-$REV$TAG << EOM
PACKAGE DESCRIPTION:
yt-dl: yt-dlp (YouTube video download utility)
yt-dlp:
yt-dlp: yt-dlp is a small command-line program to download videos
yt-dlp: from YouTube.com.  It's licensed under the MIT License.
yt-dlp:
yt-dlp: Homepage: http://www.yt-dl.org/
yt-dlp:
yt-dlp:
yt-dlp:
yt-dlp:
yt-dlp:
FILE LIST:
EOM

find * | grep -v var >> $PKGINFO/$PKG-$VER-noarch-$REV$TAG

# make slackware pkg
#cd $BUILD && makepkg -l n -c n $WRKDIR/$PKG-$VER-noarch-$REV$TAG.txz

# make module
#cd $WRKDIR && txz2xzm $PKG-$VER-noarch-$REV$TAG.txz 
cd $WRKDIR && dir2xzm $PKG $PKG-$VER-noarch-$REV$TAG.xzm
 
echo "Your module $txtgreen $PKG-$VER-noarch-$REV$TAG.xzm $rst is ready in $WRKDIR "
cyan "Please copy it to your modules folder or somewhere safe." 

cleanup
