#!/bin/sh

distpkgs=/mod/lib/python2.7/dist-packages

cfgfile='/mod/etc/youtube-dl.conf'
oldcfgfile="${cfgfile}.old"

# the default settings
def_settings() {
    cat << EOM
    --restrict-filenames
    --prefer-ffmpeg
    -f|--format "best[height<=?1080][fps<=?30]"
    -o|--output "$outdir/%(title)s.%(ext)s"
EOM
}

is_set() { # option
    # -w whole words -q just set return code -E extended regexp
    [ -f "$cfgfile" ] && grep -wq -E -e "($1)" "$cfgfile"
}

case "$(cat /etc/model)" in
HDR)
    outdir='/mnt/hd2/My Video'
    ;;
*)  # HD
    outdir='/media/drive1/Video'
    ;;
esac

settings="$(mktemp)"
def_settings | 
    while read opt val; do
        # only add settings that aren't already set
        if ! is_set "$opt"; then
            echo "${opt%%|*}" "$val" >>"$settings"
        fi
    done
if [ -s "$settings" ]; then
    if [ -f "$cfgfile" ]; then
        cp "$cfgfile" "$oldcfgfile"
        echo "Your youtube-dl settings file has been updated and"
        echo "the previous settings file saved as $oldcfgfile"
    fi
    cat "$settings" >>"$cfgfile"
fi
rm "$settings"
sed -i 's/fps<=?30/fps<=?60/' "$cfgfile"

# make python recognise the distribution pkg directory
patch_python() {
    profile=/mod/etc/profile/python
    if ! grep -qF "$distpkgs" "$profile"; then
        printf 'export PYTHONPATH="%s"\n' "$distpkgs" >> "$profile"
        printf "\nLog out and in again to set PYTHONPATH\n\n"
    fi
}
patch_python

find "${distpkgs}/youtube_dl" -name '*.pyc' -exec rm -f "{}" \;

# remove pre-20201112 installation
for tag in /tmp/.ytdl_*; do
    [ -e "$tag" ] || continue
    echo "$tag" |
     ( while IFS=_ read _ ver _; do 
        if [ "$ver" -lt 20201112 -a -e "${distpkgs}/youtube-dl" ]; then
            rm -f "$tag"
            find "${distpkgs}/youtube-dl" -name '*.pyc' -exec rm -f "{}" \;
            rmdir "${distpkgs}/youtube-dl" || true
            exit
        fi
       done )
done

# background compile 
youtube-dl --version >/dev/null &

exit 0

