#!/bin/bash

# This program manages and configures eos-update-notifier (= $TARGET_PROG) with a small GUI.

ERROR() { echo "$progname: error: $1" >&2 ; }
DIE()   { ERROR "$1" ; exit 1 ; }

export TARGET_PROG=eos-update-notifier

GetLibCode() {
    local libcode=/usr/share/endeavouros/scripts/eos-script-lib-yad
    source $libcode || DIE "loading $libcode failed."
    export -f eos_yad
    export -f eos_yad_nothing_todo
    AssignIconVariables_in_eos_bash_shared
}

ServiceAction() {
    local action="$1"
    case "$action" in
        disable)
            systemctl --user stop $TARGET_PROG.timer
            systemctl --user disable $TARGET_PROG.timer
            eos_yad_nothing_todo "<tt>$TARGET_PROG ${action}d</tt>" 5
            ;;
        enable)
            systemctl --user enable $TARGET_PROG.timer
            systemctl --user start $TARGET_PROG.timer
            eos_yad_nothing_todo "<tt>$TARGET_PROG ${action}d</tt>" 5
            ;;
        status)
            $TARGET_PROG --show-timer
            ;;
    esac
}
export -f ServiceAction

Main()
{
    local progname="$(basename "$0")"
    local Editor=""

    [ "$progname" = "${TARGET_PROG}-configure" ] || DIE "internal problem with program name"

    GetLibCode
    Editor="$(EosSudoEditor)"

    local cmd=(
        eos_yad
        --form --title="Configure $TARGET_PROG"
        --image=$ICO_PREFERENCES_SYSTEM
        --text="Configure and manage features of $TARGET_PROG"
        # --width=420
        --columns=2
        --use-interp
        --align-buttons
        --buttons-layout=center

        --field="Edit config!$ICO_EDIT_CONFIG!<tt>View and modify configuration file /etc/$TARGET_PROG.conf with '$Editor'</tt>":fbtn
               "/usr/bin/RunInTerminalEx $EOS_ROOTER '$Editor /etc/$TARGET_PROG.conf'"
        --field="Schedule!$ICO_SCHEDULE!<tt>View and modify the schedule of update checks</tt>":fbtn
               "/usr/bin/$TARGET_PROG --conf"
        --field="Reset!$ICO_RESET!<tt>Reset $TARGET_PROG's systemd service files to defaults</tt>":fbtn
               "/usr/bin/RunInTerminal /usr/bin/$TARGET_PROG --init-force"
        --field="Operation test!$ICO_OPERATION_TEST!<tt>Run $TARGET_PROG now</tt>":fbtn
               "/usr/bin/RunInTerminal /usr/bin/$TARGET_PROG --systemd -iw=0s"

        # --button="Changelog!help-about!<tt>Show changelog of $TARGET_PROG</tt>":"/usr/bin/$TARGET_PROG --changelog"
        --button="Disable!$ICO_NOTIFICATION_DISABLE!Disable $TARGET_PROG service timer":"ServiceAction disable"
        --button="Enable!$ICO_NOTIFICATION!Enable $TARGET_PROG service timer":"ServiceAction enable"
        --button="Status!$ICO_INFO!Show status of $TARGET_PROG service timer":"ServiceAction status"
        --button="yad-quit!!<tt>Quit now</tt>"
    )

    "${cmd[@]}"
}

Main "$@"
