#!/bin/sh
# TODO:
# - Check if installation is successful
# - Check if already installed
# - Uninstall
# - Allow to use already set variables
# main
set_lang
set_version
set_menu

menu info "$PROMPT_WELCOME"

if ! command -v curl > /dev/null ; then
    menu error "$PROMPT_ERR_DEPS curl"
    exit 1
fi

SERIAL="${SERIAL:=$(menu entry "$PROMPT_SERIAL")}"

if [ -z "$SERIAL" ] ; then
    menu error "$PROMPT_ERR_SERIAL"
    exit 1
fi

ARCHIVE="$(get_archive)"
TEMPKEY="${ARCHIVE##* }"
FILE="${ARCHIVE%% *}"

DOWNLOAD_URL="$(
    printf 'https://soportefirmadigital.com/sfdj/getiso.aspx?tempkey=%s' \
        "$TEMPKEY"
)"

SIZE="$(curl -sI "$DOWNLOAD_URL" |
    sed '/[Cc]ontent-[Ll]ength/!d;s/^.*: //g' |
    awk '{$1/=1024;printf "%d",$1}'
)"

if [ "$SIZE" -lt 500 ] || [ -z "$FILE" ] ; then
    menu error "$PROMPT_ERR_DOWNLOAD"
    exit 1
fi

SAVE_DIR="/tmp/soportefirmadigital"
SAVE_FILE="$SAVE_DIR/$FILE"
mkdir -p "$SAVE_DIR"

if [ "$MENU" = "zenity" ] ; then
    (curl -sL "$DOWNLOAD_URL" -o "$SAVE_FILE") &
    while true ; do
        sleep 0.5
        DOWN="$(du "$SAVE_FILE" 2>/dev/null | awk '{print $1}')"
        [ -z "$DOWN" ] && DOWN=0
        r=$(((DOWN*10000)/SIZE))
        printf '%d\n' ${r%??}
    done | zenity --title "$TITLE" --text "$PROMPT_DOWNLOAD" --progress --auto-close

elif [ "$MENU" = "term" ] ; then
    menu info "$PROMPT_DOWNLOAD" && echo
    curl "$DOWNLOAD_URL" -o "$SAVE_FILE" --progress-bar

fi

# This way is better in this case
# shellcheck disable=SC2009
ACTIVE="$(ps -t | grep 'curl.*soportefirmadigital' | sed '/grep/d')"
ACTIVE="${ACTIVE# }"
ACTIVEID="${ACTIVE%% *}"

if [ -n "$ACTIVE" ] ; then
    menu error "$PROMPT_ERR_DOWNLOAD"
    echo_debug "Killing process ID: $ACTIVEID from: $ACTIVE" # DEBUG
    kill "$ACTIVEID"
    exit 1
fi

SUDO_PASSWORD="${SUDO_PASSWORD:=$(menu pass "$PROMPT_PASS_DEPS_INSTALL")}"

if [ -z "$SUDO_PASSWORD" ] || ! tsudo whoami >/dev/null 2>&1 ; then
    menu error "$PROMPT_ERR_DEPS_INSTALL"
    exit 1
fi

if [ "$MENU" = "zenity" ] ; then
    # Attempt to install, forward output to program
    # but keep exit code of install function
    ( ( ( (install_certs; echo $? >&3) |
        zenity --title "$TITLE" --text "$PROMPT_DEPS_INSTALL" --progress --pulsate --auto-close >&4) 3>&1 ) |
        (read -r xs; exit "$xs") ) 4>&1
    #install_certs # Just run this instead to see debug info # DEBUG
    # Ignore as this is needed for this "workaround"
    # shellcheck disable=SC2181
    if [ "$?" != "0" ] ; then
        menu error "$PROMPT_ERR_DEPS_INSTALL"
        exit 1
    fi

elif [ "$MENU" = "term" ] ; then
    menu info "$PROMPT_DEPS_INSTALL" && echo
    ! install_certs && menu error "$PROMPT_ERR_DEPS_INSTALL" && exit 1

fi

menu info "$PROMPT_END_SUCCESS\n"

exit 0