#!/bin/bash

TEXTDOMAINDIR=/usr/share/locale
TEXTDOMAIN=aCSTV.sh
export TEXTDOMAINDIR  # new circuitous gettext style applied
export TEXTDOMAIN
source gettext.sh

# this script was cut and adapted from our way more powerful internal aCSTV
# packaging preparing updater, so don't wonder about all the pomp and circumstance.

mode="postinst" # set mode either to "postinst" od "packaging". make sure to
                # uncomment/comment the respective lines 101/102 and 147/148 when changing mode
                # set target folder for packaging in line 20 according to your needs.

# points to folder where the package stores aCSTV stations lists stuff
if [ "$mode" != "packaging" ]; then
    targetfolder="/usr/local/lib/aCSTV/Stationslisten"  # for postinst
else
    targetfolder="./paket/acstv-stations/usr/local/lib/aCSTV/Stationslisten"  # for packaging
fi

# temp files
temporaerdatei_14="/dev/shm/aCSTV-$$14.tmp"
temporaerdatei_16="/dev/shm/aCSTV-$$16.tmp"
temporaerdatei_22="/dev/shm/aCSTV-$$22.tmp"
temporaerdatei_23="/dev/shm/aCSTV-$$23.tmp"
temporaerdatei_24="/dev/shm/aCSTV-$$24.tmp"

# we're going to change working dir while processing
current="$(pwd)"

# cleanup function
aufräumen () {
    rm -f "$temporaerdatei_14"
    rm -f "$temporaerdatei_16"
    rm -f "$temporaerdatei_22"
    rm -f "$temporaerdatei_23"
    rm -f "$temporaerdatei_24"
    cd "$current"
}
trap aufräumen EXIT

# ignored in packaging mode.
if ! [ "$mode" = "packaging" ]; then
    # retrieve user language and country needed for processing.
    ui_land="$(locale | grep ^LANG= | cut -d= -f2 | cut -d. -f1 | cut -d_ -f2)"
    ui_lang_4="$(locale | grep ^LANG= | cut -d= -f2 | cut -d. -f1)"
    # ui_lang_2="$(locale | grep ^LANG= | cut -d= -f2 | cut -d_ -f1)"

    [ "$ui_lang_4" = "de_DE" ] && exit 0 # try builtin list first if country = DE and language = de, user can update from aCSTV settings
    #[ "$ui_land" = "DE" ] && exit 0 # try builtin list first for country = DE, user can update from aCSTV settings
    #[ "$ui_lang_2" = "de" ] && exit 0 # try builtin list first for language = de, user can update from aCSTV settings

    #echo $"The stations lists file(s) in this package might be outdated.""
#"$"You can update the lists later always from within aCSTV settings.""
#"$"Would you like to update them all now from iptv-org?""  "$"[Y]es""/"$"[N]o"

    # new gettext syntax since xgettext complains about $"..." style. renders code uncomprehensible.
    eval_gettext "The stations lists file(s) of your country might be outdated."
    echo ""
    eval_gettext "You can update the lists later always from within aCSTV settings."
    echo ""
    eval_gettext "Would you like to update them now from iptv-org?"
    echo -n "  "
    eval_gettext "[Y]es"
    echo -n "/"
    eval_gettext "[N]o"
    echo ""
    while true; do
        read -N1 -s -r yn
        case $yn in
            # [$"y"$"Y"] ) update=true; break;;
            # [$"n"$"N"] ) update=false; break;;
            ([$(eval_gettext "y")$(eval_gettext "Y"])) update=true; break;;
	        ([$(eval_gettext "n")$(eval_gettext "N"])) update=false; break;;
	        * ) :;;
        esac
    done
else
    update=true  # always true for packaging
fi

if $update; then
    mkdir -p "$targetfolder"
    cd "$targetfolder"  # this way it is easier to set the symbolic links later from within the loop.
    # for postinst: create list file containing all locales to be processed, one line per entry
    [ "$mode" = "postinst" ] && echo "$ui_lang_4" > "$temporaerdatei_24"

    # for packaging: calculate list of languages supported by system and corresponding countries
    if [ "$mode" = "packaging" ]; then sed -n 's/^\([[:alpha:]]\{1,3\}_[[:alpha:]]\{1,3\}\)..*$/\1/p' /usr/share/i18n/SUPPORTED | uniq > "$temporaerdatei_24"; fi

    # fetch list of available stations lists and create working list of countries from it
    wget -O "$temporaerdatei_22" 'https://github.com/iptv-org/iptv/tree/master/streams'
    if [ $? -ne 0 ]; then
        echo "Error: list of stations lists not found on server"
    else
        cat "$temporaerdatei_22" | tr ',' '\n' | tr '[' '\n' |sed -n 's/{"name":"\(..*\)\.m3u"/\1/p' > "$temporaerdatei_23"
        # process matching lists
        count=0
        for st_land in $( grep ^${ui_land,,} "$temporaerdatei_23"); do  # for postinst
        #while read st_land; do                                          # for packaging
            stationsliste="${st_land^^}.lst"
            wget -O "$temporaerdatei_16" "https://github.com/iptv-org/iptv/raw/master/streams/$st_land.m3u"  # download country specific raw list
            [ $? -ne 0 ] && continue
            # reformat raw list file
            sed -i -e "/#EXTM3U\|EXTVLCOPT/d" "$temporaerdatei_16"
            sed -n -e "/^#EXTINF:/{s/..*,\(..*\) *\((\.*\| *\)\(\[.*\| *\)\((.*\| *\).*$/\1/;s/ (..*)//;s/ \[..*\]//;s/ *//g;N;s/\n/=\x27/;s/$/\x27/p}" "$temporaerdatei_16" > "$temporaerdatei_14"
            rm -f "$temporaerdatei_16"  # remove raw list file
            awk '!seen[$0]++' "$temporaerdatei_14" > "$temporaerdatei_16"   # remove duplicate entries
            cp "$temporaerdatei_16" "$temporaerdatei_14" # create working copy
            i=0
            while read k; do
                let $((i++))
                [ ${k::1} == "#" ] && continue  # skip comment lines
                m="$(cut -d= -f1 <<<"$k")"      # extract token
                if [ $(grep -c "^$m=" "$temporaerdatei_14") -gt 1 ]; then   # check for duplicate tokens...
                    r=1
                    while [ $(grep -c "^$m$r=" "$temporaerdatei_14") -ge 1 ]; do
                        let $((r++))
                    done
                    sed -i "/${k//\//\\/}/s/^\(${m//\//\\/}\)/\1$r/" "$temporaerdatei_14" # ...and add a counter to them.
                fi                
            done <"$temporaerdatei_16"
            rm -f "$temporaerdatei_16"
            # check for empty list files
            if ! grep -q '[^[:space:]]' "$temporaerdatei_14"; then rm "$temporaerdatei_14"; continue; fi
            # move completed stations list in place
            mv "$temporaerdatei_14" "./""$stationsliste"
            rm -f "$temporaerdatei_14"
            # add proper ISO639-1 language code to ISO-3166-1 countries to generate proper list names for usage in aCSTV
            st_land2=${st_land%%_*}
            if grep ..*_${st_land2^^} "$temporaerdatei_24" >/dev/null; then
                for i in $(grep ..*_${st_land2^^} $temporaerdatei_24); do
                    # create symbolic links for languages matching known countries
                    [ -h "./""${i%_*}_""$stationsliste" ] && unlink "./""${i%_*}_""$stationsliste"
                    [ -f "./""${i%_*}_""$stationsliste" ] && rm -f "./""${i%_*}_""$stationsliste"
                    ln -s "./""$stationsliste" "./""${i%_*}_""$stationsliste"
                done
            else 
                # create symbolic links for unknown countries
                [ -h "./""??_""$stationsliste" ] && unlink "./""??_""$stationsliste"
                [ -f "./""??_""$stationsliste" ] && rm -f "./""??_""$stationsliste"
                ln -s "./""$stationsliste" "./""??_""$stationsliste"
            fi
            let $((count++))
        #done < "$temporaerdatei_23"   # for packaging
        done                          # for postinst
    [ $count -lt 1 ] && (eval_gettext "No matching stations list found for your country."; echo " ($ui_lang_4)")
    fi
fi

exit 0
