#!/usr/bin/env bash

DESKTOP_FILE=~/.local/share/applications/pyradio.desktop

function help_terminal(){
echo "Suitable terminals are:
   gnome-terminal, mate-terminal, xfce4-terminal, lxterminal, terminator,
   termite, termit, kitty, alacritty, sakura, roxterm, tilix, lilyterm,
   st, xst, rxvt, uxterm, xterm
Please make sure that one of them is installed."
}

function help(){
echo "Usage: $(basename $0) [-t TERMINAL]"
echo "
This script is part of PyRadio

It will update the local Dekstop File, so that it uses a suitable terminal for
the execution of PyRadio.
"

help_terminal

echo "
Available options:
    -t   TERMINAL
         Use this terminal for Desktop file instead of the auto-detected one.
         Use \"none\" to reset to the default terminal.
         Use \"auto\" to reset to the auto-detected one.
    -p   PARAMETER
         A number of parameters to be passed to PyRadio, for example:
                -p "-p3 -t light"
    -d   DISTRO_DESKTOP_FILE
         If this is a distribution package, and the Desktop File is not
         installed under /usr/share/applications, this parameter will
         tell the script where it is installed.
    -z   Delete the Desktop file before doing anything else.
    -s   Show Desktop file and exit.

For passing the command parameter, the script will use \"-e\" for all terminals,
so that an executable line will be constracted.
Example:
    kitty -e pyradio

If your terminal of choise uses a different way to accept the command, please
include it in the TERMINAL value. For example, if the command parameter for
the terminal \"my_term\" is \"-S\", execute as follows:

    ./fix_pyradio_desktop_file -t \"my_term -S\"
"
}

function get_data_dir(){
    local CHK_XDG_DATA_DIR
    local CHK_XDG_STATE_DIR
    SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
    CFG_FILE=$(dirname $"$SCRIPT_DIR")"/pyradio/config"
    if [ -e "$CFG_FILE" ]
    then
        XDG="$(sed 's/[A-Z]/\l&/' "$CFG_FILE" | grep 'xdg_compliant = true')"
    fi
    if [ -z "$XDG" ]
    then
        CHK_XDG_DATA_DIR=${XDG_DATA_HOME-"$HOME"/.local/share/pyradio}
        CHK_XDG_STATE_DIR=${XDG_DATA_HOME-"$HOME"/.local/state/pyradio}
        if [ -e ${CHK_XDG_DATA_DIR} ] && [ -e "${CHK_XDG_STATE_DIR}" ]
        then
            XDG=true
        fi
    fi
    if [ -z "$XDG" ]
    then
        DATA_DIR=~/.config/pyradio/data
    else
        DATA_DIR="${XDG_DATA_HOME-"$HOME"/.local/share/pyradio}"
    fi
    mkdir -p "$DATA_DIR" 2>/dev/null
}

function write_desktop_file(){
    if [ -z "${REQ_TERMINAL}" ]
    then
        TERMINAL_LINE="Terminal=true"
    else
        REQ_TERMINAL="${REQ_TERMINAL}"' '
        TERMINAL_LINE="Terminal=false"
    fi

    echo "[Desktop Entry]
Version=1.0
Type=Application
Name=PyRadio
GenericName=Terminal Radio Player
Comment=Curses based Radio Player" > "${DESKTOP_FILE}"

    echo "TryExec=${PROGRAM}" >> "${DESKTOP_FILE}"
    EXEC_LINE=$(echo "Exec=${REQ_TERMINAL}${PROGRAM}" | sed -e 's/Exec=  */Exec=/' -e 's/  / /g')
    if [ -z "${PARAM}" ]
    then
        echo "$EXEC_LINE" >> "${DESKTOP_FILE}"
    else
        # set -x
        # echo "EXEC_LINE = ${EXEC_LINE}"
        # echo "PARAM = ${PARAM}"
        PARAM=" ${PARAM//_/-}"
        # echo "PARAM = ${PARAM}"
        NEW_EXEC_LINE="${EXEC_LINE} ${PARAM}"
        # echo "NEW_EXEC_LINE =  $NEW_EXEC_LINE"
        NEW_EXEC_LINE=$(echo "${NEW_EXEC_LINE}" | sed "s|${PROGRAM}|'${PROGRAM}|")
        NEW_EXEC_LINE="${NEW_EXEC_LINE}""'"
        NEW_EXEC_LINE="$(echo "${NEW_EXEC_LINE}" | sed s/\'/\"/g)"
        echo "$NEW_EXEC_LINE" >> "${DESKTOP_FILE}"
    fi
    echo "Icon=${DATA_DIR}/pyradio.png" >> "${DESKTOP_FILE}"
    echo "${TERMINAL_LINE}" >> "${DESKTOP_FILE}"
    echo "Categories=Network" >> "${DESKTOP_FILE}"

    if [ -e /usr/share/applications/pyradio.desktop ] || \
        [ -e /usr/loacal/share/applications/pyradio.desktop ] || \
        [ -e "${ORIGINAL_DESKTOP_FILE}" ]
    then
        sed -i 's/Name=PyRadio/& - Local/' "${DESKTOP_FILE}"
    fi
}

function get_terminal_from_desktop_file(){
    # try to get terminal from a desktop file
    # passed as $1
    unset DET_TERMINAL
    unset DET_COMMAND
    if [ -e "$1" ]
    then
        if [[ ! -z $(grep 'Terminal=false' "$1") ]]
        then
            line=$(sed -n '/^Exec=/p' "$1")
            line="${line/Exec=/}"
            OFS="${IFS}"
            IFS=' '
            read -ra newarr <<< "$line"
            IFS="${OFS}"
            if (( ${#newarr[@]} > 1 ))
            then
                # I have a terminal
                DET_TERMINAL="${newarr[0]}"
                DET_COMMAND="${newarr[1]}"
            fi
        fi
    fi
    [ -z "${DET_TERMINAL}" ] || echo "  Last used terminal: ${DET_TERMINAL}"
}

function get_req_terminal(){
    if [ -z "${REQ_TERMINAL}" ]
    then
        for n in ~/.local/share/applications/pyradio.desktop \
                /usr/share/applications/pyradio.desktop \
                /usr/local/share/applications/pyradio.desktop \
                "${ORIGINAL_DESKTOP_FILE}"
        do
            get_terminal_from_desktop_file "$n"
            LOCAL_TERMINAL="${DET_TERMINAL}"
            LOCAL_COMMAND="${DET_COMMAND}"
            if [ ! -z "${LOCAL_TERMINAL}" ]
            then
                REQ_TERMINAL="${LOCAL_TERMINAL}"
                REQ_COMMAND="${LOCAL_COMMAND}"
                break
            fi
        done

        if [ ! -z "${REQ_TERMINAL}" ]
        then
            REQ_TERMINAL="${REQ_TERMINAL} ${REQ_COMMAND}"
        fi
    fi
    if [ "${REQ_TERMINAL}" == "none" ]
    then
        unset REQ_TERMINAL
    fi
}

function get_program(){
    PROGRAM=$(which pyradio)
    if [ -z "$PROGRAM" ]
    then
        if [ -e /home/"$USER"/.local/bin/pyradio ]
        then
            PROGRAM=/home/"$USER"/.local/bin/pyradio
        else
            PROGRAM=pyradio
        fi
    fi
}

function get_terminal(){
    # look for a valid terminal
    for n in  \
        "gnome-terminal --help" \
        "mate-terminal --help" \
        "xfce4-terminal -V" \
        "lxterminal -v" \
        "terminator -v" \
        "termite -v" \
        "kitty -v" \
        "alacritty -V" \
        "sakura -v" \
        "roxterm --help" \
        "tilix -v" \
        "lilyterm -v" \
        "st -v" \
        "xst -v" \
        "rxvt  -v"\
        "urxvt  -v"\
        "uxterm -v" \
        "xterm -v"
    do
        $n 2>/dev/null 1>&2 && {
            REQ_TERMINAL="${n/ */}"
            COMMAND='-e'
            if [ "$REQ_TERMINAL" = "gnome-terminal" ]; then COMMAND='--';fi
            break
        }
    done

    if [ ! -z "${REQ_TERMINAL}" ];then
        REQ_TERMINAL=${REQ_TERMINAL}" $COMMAND"
    fi
}

while [[ $# -gt 0 ]]
do
    key="$1"
    case $key in
        -h|--help)
            help
            exit
            ;;
        -s)
            echo "Printing: ${DESKTOP_FILE}"
            echo
            cat "${DESKTOP_FILE}"
            echo
            exit
            ;;
        -d)
            shift
            if [ ! -r "$1" ];then
                echo "Error in parameter -d: Desktop file not found..."
                exit 1
            else
                ORIGINAL_DESKTOP_FILE="$1"
            fi
            shift
            ;;
        -t)
            shift
            if [ -z "$1" ];then
                echo "Error: No terminal specified..."
                echo
                exit 1
            fi
            REQ_TERMINAL="$1"
            if [ "${REQ_TERMINAL}" = "auto" ]
            then
                echo "Auto-detecting terminal..."
                [ -z "${TERMINAL}" ] && get_terminal || REQ_TERMINAL="${TERMINAL}"
                if [ -z "${REQ_TERMINAL}" ]
                then
                    echo "No suitable terminal can be detected in this system..."
                    echo
                    help_terminal
                    echo
                    exit 1
                else
                    echo "  Auto-detecteted terminal: ${REQ_TERMINAL/ */}"
                    if [ "${REQ_TERMINAL}" = "gnome-terminal" ]
                    then
                        REQ_TERMINAL="${REQ_TERMINAL} --"
                    else
                        REQ_TERMINAL="${REQ_TERMINAL} -e"
                    fi
                fi
            else
                if [ "${REQ_TERMINAL}" != "none" ]
                then
                    if [[ "${REQ_TERMINAL}" != *" "*  ]]
                    then
                        if [ "${REQ_TERMINAL}" = "gnome-terminal" ]
                        then
                            REQ_TERMINAL="${REQ_TERMINAL} --"
                        else
                            REQ_TERMINAL="${REQ_TERMINAL} -e"
                        fi
                    fi
                fi
            fi
            shift
            ;;
        -p)
            shift
            PARAM="$1"
            [ -z "${PARAM}" ] && {
                echo "Error: No parameter specified..."
                exit
            }
            shift
            ;;
        -z)
            ZERO=1
            shift
            ;;
        *)    # unknown option
            POSITIONAL+=("$1") # save it in an array for later
            shift # past argument
            ;;
    esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters

get_data_dir
echo "Installing Desktop file ...   "
[ -z ${ZERO} ] && rm ${DESKTOP_FILE}
# set -x
get_req_terminal
get_program
write_desktop_file

