#!/usr/bin/env bash

:<<'COMMENT == ====================================================='
COMMENT == =====================================================

init(){
    export TEXTDOMAIN=$(basename ${0%.*})
    export TEXTDOMAINDIR="/usr/share/locale"

    export LC_ALL="ru_RU.UTF-8"
    export LANG="$LANG"
    export LANGUAGE="en_US:en:ru_RU:ru"
    export LC_PAPER="en_US.UTF-8"
    export LESSCHARSET="utf-8"
    export MM_CHARSET="utf-8"
}
export -f init
init

i18n() {
    local key="$1"; shift
    printf "$(gettext -s "$key")" "$@"
}
export -f i18n

export XDG_SEAT_PATH="/org/freedesktop/DisplayManager/Seat0"
export DISPLAY=:0.0
export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$UID/bus"
export cmd_pid="123"
export cycle_pid="321"


export LOCAL_DATA_DIR="/dev/shm/$(basename ${0})"
mkdir -p ${LOCAL_DATA_DIR}
export MAIN_DIALOG_FILE="${LOCAL_DATA_DIR}/MAIN_DIALOG_FILE_${USER}_${BASHPID}.gtkdialog"
[ -z ${GTKDIALOG:-} ] && GTKDIALOG=gtkdialog
export tmpTIMER="/dev/shm/ubshutdown_timer.tmp"
export tmpCMDPID="/dev/shm/ubshutdown_cmdpid.tmp"
export tmpCCLPID="/dev/shm/ubshutdown_ccltimer.tmp"
touch "$tmpTIMER" "$tmpCMDPID" "$tmpCCLPID"


trap "exit_cmd" EXIT

exit_cmd(){
    echo -e "\n$(i18n "Clear data...")"
    rm -rf $LOCAL_DATA_DIR # $tmpCMDPID $tmpCCLPID
}
export -f exit_cmd

cat <<-EODECK > ${MAIN_DIALOG_FILE}
<window title="$(i18n "Log out %s" "$(whoami)")"
        width-request="650"
        height-request="300"
        icon-name="ubshutdown-timer"
        resizable="false"
        can-focus="false"
        auto-refresh="true"
        decorated="true"
        name="mainWin1"
        window-position="1">
    <vbox>
        <hbox>
            <button visible="true"
                    can-focus="true"
                    space-fill="true"
                    space-expand="true"
                    height-request="85"
                    width-request="100"
                    image-position="2"
                    theme-icon-size="55">
                <label>$(i18n "Logout")</label>
                <input file icon="xfsm-logout"></input>
                <action>commands_ubshutdown "logout" "\$vHRS" "\$vMIN" "\$vSEC"</action>
            </button>
            <button visible="true"
                    can-focus="true"
                    space-fill="true"
                    space-expand="true"
                    height-request="85"
                    width-request="100"
                    image-position="2"
                    theme-icon-size="55">
                <label>$(i18n "Reboot")</label>
                <input file icon="xfsm-reboot"></input>
                <action>commands_ubshutdown "reboot" "\$vHRS" "\$vMIN" "\$vSEC"</action>
            </button>
        </hbox>
        <hbox>
            <button visible="true"
                    can-focus="true"
                    space-fill="true"
                    space-expand="true"
                    height-request="85"
                    width-request="100"
                    image-position="2"
                    theme-icon-size="55">
                <label>$(i18n "Poweroff")</label>
                <input file icon="xfsm-shutdown"></input>
                <action>commands_ubshutdown "poweroff" "\$vHRS" "\$vMIN" "\$vSEC"</action>
            </button>
            <button visible="true"
                    can-focus="true"
                    space-fill="true"
                    space-expand="true"
                    height-request="85"
                    width-request="100"
                    image-position="2"
                    theme-icon-size="55">
                <label>$(i18n "Changing the user")</label>
                <input file icon="xfsm-switch-user"></input>
                <action>commands_ubshutdown "changeuser" "\$vHRS" "\$vMIN" "\$vSEC"</action>
            </button>
            <button visible="true"
                    can-focus="true"
                    space-fill="true"
                    space-expand="true"
                    height-request="85"
                    width-request="100"
                    image-position="2"
                    theme-icon-size="55">
                <label>$(i18n "Lock")</label>
                <input file icon="xfsm-hibernate"></input>
                <action>commands_ubshutdown "lock" "\$vHRS" "\$vMIN" "\$vSEC"</action>
            </button>
        </hbox>
        <hseparator>
        </hseparator>
        <hbox>
            <text label=""
                  height-request="10">
            </text>
        </hbox>
        <hbox>
            <text label="$(i18n "Timer"):"
                  space-fill="false"
                  space-expand="false">
            </text>
            <spinbutton width-request="50"
                        range-min="0"
                        range-max="23"
                        range-step="1"
                        visible="true"
                        space-expand="false"
                        space-fill="false">
                <variable>vHRS</variable>
            </spinbutton>
            <text label=":"
                  space-fill="false"
                  space-expand="false">
            </text>
            <spinbutton width-request="50"
                        range-min="0"
                        range-max="59"
                        range-step="1"
                        visible="true"
                        space-expand="false"
                        space-fill="false">
                <variable>vMIN</variable>
            </spinbutton>
            <text label=":"
                  space-fill="false"
                  space-expand="false">
            </text>
            <spinbutton width-request="50"
                        range-min="0"
                        range-max="59"
                        range-step="1"
                        visible="true"
                        space-expand="false"
                        space-fill="false">
                <variable>vSEC</variable>
            </spinbutton>
            <text width-request="125"
                  label="">
            </text>
            <text visible="true"
                  width-request="250"
                  auto-refresh="true"
                  can-focus="false"
                  halign="start"
                  space-expand="false"
                  space-fill="false">
                <input file>$tmpTIMER</input>
            </text>
        </hbox>
        <hbox>
            <button visible="true"
                    can-focus="true"
                    space-fill="false"
                    space-expand="false">
                <label>$(i18n "Cancel the action")</label>
                <action>cancel_action</action>
            </button>
        </hbox>
    </vbox>
</window>
EODECK

cancel_action(){
    local cmd_pid=$(cat "$tmpCMDPID")
    local cycle_pid=$(cat "$tmpCCLPID")

    if [ -n "$cycle_pid" ] && [ -n "$cmd_pid" ]; then
        kill "$cmd_pid" "$cycle_pid"
        echo -n > "$tmpTIMER"
        echo -n > "$tmpCMDPID"
        echo -n > "$tmpCCLPID"
    fi
}
export -f cancel_action

commands_ubshutdown(){
    local cmd_pid=$(cat "$tmpCMDPID")
    local cycle_pid=$(cat "$tmpCCLPID")
    local _COMMAND="$1"
    local _time=""
    local lvTIME="$(date | cut -d ' ' -f5)"
    local lvTIME_HRS="$(echo "$lvTIME" | cut -d ':' -f1)"
    [ -n "$(echo "$lvTIME_HRS" | grep "^0[0-9]$")" ] && lvTIME_HRS="${lvTIME_HRS:1}"
    local lvTIME_MIN="$(echo "$lvTIME" | cut -d ':' -f2)"
    [ -n "$(echo "$lvTIME_MIN" | grep "^0[0-9]$")" ] && lvTIME_MIN="${lvTIME_MIN:1}"
    local lvTIME_SEC="$(echo "$lvTIME" | cut -d ':' -f3)"
    [ -n "$(echo "$lvTIME_SEC" | grep "^0[0-9]$")" ] && lvTIME_SEC="${lvTIME_SEC:1}"

    _time=$(($2*3600+$3*60+$4))
    # if [ $lvTIME_HRS -lt $2 ] || [ $lvTIME_MIN -lt $3 ] || [ $lvTIME_SEC -lt $4 ]; then
    #     _time=$((($2*3600+$3*60+$4)-($lvTIME_HRS*3600+$lvTIME_MIN*60+$lvTIME_SEC)))
    # else
    #     _time=$((86400-($lvTIME_HRS*3600+$lvTIME_MIN*60+$lvTIME_SEC)+($2*3600+$3*60+$4)))
    # fi
    # local timer_time=$_time

    if [ -n "$cycle_pid" ] && [ -n "$cmd_pid" ]; then
        kill "$cmd_pid" "$cycle_pid"
        echo -n > "$tmpTIMER"
    fi

    commands_ubshutdown_child "$_COMMAND" "$_time" & cmd_pid=$!
    timer "$_time" "$_COMMAND" && rm -f "$tmpTIMER" & cycle_pid=$!
    disown "$cmd_pid"
    disown "$cycle_pid"
    echo "$cmd_pid" > "$tmpCMDPID"
    echo "$cycle_pid" > "$tmpCCLPID"
}
export -f commands_ubshutdown

commands_ubshutdown_child(){
    case "$1" in
        "logout")
            if [ $2 -ge 60 ]; then
                sleep $((${2}-60))s
                notify-send "UBShutdown-timer" "$(i18n "Your pc will logged out in 1 minute!")" --icon=ubshutdown-timer
                sleep 60s
                xfce4-session-logout --logout --fast
            else
                notify-send "UBShutdown-timer" "$(i18n "Your pc will logged out in 1 minute!")" --icon=ubshutdown-timer
                sleep ${2}s
                xfce4-session-logout --logout --fast
            fi
        ;;
        "reboot")
            if [ $2 -ge 60 ]; then
                sleep $((${2}-60))s
                notify-send "UBShutdown-timer" "$(i18n "Your pc will reboot in 1 minute!")" --icon=ubshutdown-timer
                sleep 60s
                shutdown -r now
            else
                notify-send "UBShutdown-timer" "$(i18n "Your pc will reboot in 1 minute!")" --icon=ubshutdown-timer
                sleep ${2}s
                shutdown -r now
            fi
        ;;
        "poweroff")
            if [ $2 -ge 60 ]; then
                sleep $((${2}-60))s
                notify-send "UBShutdown-timer" "$(i18n "Your pc will shut down in 1 minute!")" --icon=ubshutdown-timer
                sleep 60s
                shutdown -H now
            else
                notify-send "UBShutdown-timer" "$(i18n "Your pc will shut down in 1 minute!")" --icon=ubshutdown-timer
                sleep ${2}s
                shutdown -H now
            fi
        ;;
        "changeuser")
            if [ $2 -ge 60 ]; then
                sleep $((${2}-60))s
                notify-send "UBShutdown-timer" "$(i18n "Your pc will change user in 1 minute!")" --icon=ubshutdown-timer
                sleep 60s
                dm-tool switch-to-greeter
            else
                notify-send "UBShutdown-timer" "$(i18n "Your pc will change user in 1 minute!")" --icon=ubshutdown-timer
                sleep ${2}s
                dm-tool switch-to-greeter
            fi
        ;;
        "lock")
            if [ $2 -ge 60 ]; then
                sleep $((${2}-60))s
                notify-send "UBShutdown-timer" "$(i18n "Your pc will locked in 1 minute!")" --icon=ubshutdown-timer
                sleep 60s
                dm-tool lock
            else
                notify-send "UBShutdown-timer" "$(i18n "Your pc will locked in 1 minute!")" --icon=ubshutdown-timer
                sleep ${2}s
                dm-tool lock
            fi
        ;;
    esac
}
export -f commands_ubshutdown_child

timer(){
    time=$1
    cmd="$2"
    while [ $time -ge 0 ]; do 
        timer_child "$time" "$cmd"
        ((time--))
        sleep 1s
    done
    echo -n > "$tmpTIMER"
}
export -f timer

timer_child(){
    local hrs=""
    local min=""
    local sec=""
    local rmns_wo_hrs=""
    local rmns_wo_min=""
    local time=""
    local cmd="$2"
    if [ $1 -ge 3600 ]; then
        rmns_wo_hrs=$(($1%3600))
        if [ $rmns_wo_hrs -gt 0 ]; then
            hrs=$((($1-$rmns_wo_hrs)/3600))
            if [ $rmns_wo_hrs -ge 60 ]; then
                rmns_wo_min=$(($rmns_wo_hrs%60))
                if [ $rmns_wo_min -gt 0 ]; then
                    min=$((($rmns_wo_hrs-$rmns_wo_min)/60))
                    sec=$rmns_wo_min
                else
                    min=$((($rmns_wo_hrs-$rmns_wo_min)/60))
                    sec="00"
                fi
            else
                min="00"
                sec="$rmns_wo_hrs"
            fi
        else
            hrs=$((($1-$rmns_wo_hrs)/3600))
            min="00"
            sec="00"
        fi
    elif [ $1 -ge 60 ]; then
        hrs="00"
        rmns_wo_min=$(($1%60))
        if [ $rmns_wo_min -gt 0 ]; then
            min=$((($1-$rmns_wo_min)/60))
            sec=$rmns_wo_min
        else
            min=$((($1-$rmns_wo_min)/60))
            sec="00"
        fi
    else
        hrs="00"
        min="00"
        sec="$1"
    fi
    [ ${#hrs} == 1 ] && hrs="0${hrs}"
    [ ${#min} == 1 ] && min="0${min}"
    [ ${#sec} == 1 ] && sec="0${sec}"
    case "$2" in
        "logout")
            time="$(i18n "Your pc will logged out after"): "
        ;;
        "reboot")
            time="$(i18n "Your pc will reboot after"): "
        ;;
        "poweroff")
            time="$(i18n "Your pc will shut down after"): "
        ;;
        "changeuser")
            time="$(i18n "Your pc will change user after"): "
        ;;
        "lock")
            time="$(i18n "Your pc will locked after"): "
        ;;
    esac
    time+="${hrs}:${min}:${sec}"
    echo $time > "$tmpTIMER"
}
export -f timer_child

case ${1:-} in
    -d | --dump) more "${MAIN_DIALOG_FILE}" ;;
    -f | --file) $GTKDIALOG --center --file=${MAIN_DIALOG_FILE} ;;
    -v | --variable) export MAIN_DIALOG=$(cat ${MAIN_DIALOG_FILE}); $GTKDIALOG --center --program=MAIN_DIALOG ;;
    *) $GTKDIALOG --file=${MAIN_DIALOG_FILE} ;;
esac

exit 0
