#!/bin/bash
# -*- coding: utf-8 -*-

# antiX equaliser toggle
# Version 0.9
# GPL v.3
# Written 1/2024 by Robin for antiX community
# GUI design based on toggle_pipewire script by PPC
# questions, suggestions and bug reporting please to www.antixforum.com

# todo: integrate plain ALSA toggle routines for activating/deactivating alsaequal; remove dependency to wireplumber the same time.
# todo: show pipewire warning dialog not on startup, but only if really needed.
# todo: call toggle-pipewire if user asks easyeffects to be started while pipewire not running.
# todo: symbols and icons should be made named icons rather than hard coded pointing to a specific icon file.

#Set up localization for the script
TEXTDOMAINDIR=/usr/share/locale
TEXTDOMAIN=antiX-equaliser-toggle
export TEXTDOMAINDIR  # new circuitous gettext style applied
export TEXTDOMAIN
source gettext.sh

# initialise variables
export EED_STARTUP_FILE="$HOME/.desktop-session/startup"
export EED_ENTRY_STARTUP='easyeffects --gapplication-service &'
export EED_ENTRY_COMMENT='# Start easyeffects equaliser in pseudo-daemonised mode'
export EED_STARTUP_STATUS=false
export EED_ACTIVATE_ENTRY=false
export EED_ADD_ENTRY=false
export EED_REMOVE_ENTRY=false
export EED_DISABLE_ENTRY=false
export EED_HARD_BLOCKED=false
export EE_DAEMON_STATUS=false
#export EE_VISIBLE=false  # no longer needed, moved detection to later point in processing to catch status changes while we are running already

# make sure antiX startup file exists, otherwise test, sed and grep will fail.
[ ! -f "$EED_STARTUP_FILE" ] && mkdir -p ${EED_STARTUP_FILE%/*} && touch "$EED_STARTUP_FILE"

# check whether pipewire is installed and sound server up and running. Exit on error.
if ! wpctl status >/dev/null; then
   yad --window-icon=antiXac --info --fixed \
   --title="$(eval_gettext 'No Pipewire.')" \
   --borders=15 --image=antiXac --on-top --center \
   --text="<b>$(eval_gettext 'Warning!')</b>\n\n\t$(eval_gettext 'Pipewire not running.')\n\t$(eval_gettext 'Please go to antiX control centre\n\tand start Pipewire before.')\n" \
   --button="$(eval_gettext 'OK')":0
   exit 1
fi

# Activate or deactivate easyeffect's daemonised mode, depending on current status. Restore state of running GUI instance.
function toggle_daemon {
    local easyeffects_running=false
    local easyeffects_visible=false
    if ! $EE_DAEMON_STATUS; then
        # put easyeffects in it's daemonised mode. Restore it's current state (GUI started and/or minimised).
        # A running gui instance must be shut down for this.
#        if pidof easyeffects >/dev/null; then kill -15 $(pidof easyeffects); easyeffects_running=true; while pidof easyeffects >/dev/null; do sleep .1; done; fi
        if pidof easyeffects >/dev/null; then
            if xdotool search --onlyvisible --pid $(pidof easyeffects) >/dev/null; then easyeffects_visible=true; fi
            kill -15 $(pidof easyeffects)
            easyeffects_running=true
            while pidof easyeffects >/dev/null; do sleep .1; done
        fi 
        easyeffects --gapplication-service &
        while ! pidof easyeffects >/dev/null; do sleep .1; done;
        if $easyeffects_running; then
            easyeffects &
#            if ! $EE_VISIBLE; then
            if ! $easyeffects_visible; then
                # dirty workaround for xdotool search for pid reports falsely two window ID's of same name for the PID, rendering them undistinguishable. And wmctrl can't do minimise...
                # another dirty workaround for easyeffects creating some more pid's and window ids on startup, just to drop them winthin a second again.
                # and then we have to wait for slow hardware in a loop, on fast hardware loop is left immediately by break statement.
                wid_easyeffects=0; while [ "$wid_easyeffects" -eq 0 ]; do wid_easyeffects="$(($(wmctrl -l -p | grep $(pidof easyeffects) 2>/dev/null | cut -d' ' -f1)))"; [ "$wid_easyeffects" != 0 ] && break; sleep .5; done
                xdotool windowminimize $wid_easyeffects
            fi  
        fi
    else
        # close antiX Acoustic Colours before shutting down easyeffects
        if aac_pid=$(pidof -x antiX-acoustic-colours); then
            aac_yad_pid_01=$(pgrep -P $aac_pid)
            aac_yad_pid_02=$(pgrep -P $aac_yad_pid_01)
            kill 15 $aac_pid
            sleep .5
            kill 15 $aac_yad_pid_02;
        fi
        # if easyeffects running daemonised, stop it simply. will close deamonised mode and GUI both.
        easyeffects -q
    fi
}

# check easyeffects status: running in daemonised mode? GUI up, if so, minimised?
function get_status {
    export EE_DAEMON_STATUS=true
#   export EE_VISIBLE=false
#    if pidof easyeffects >/dev/null; then
#        if xdotool search --onlyvisible --pid $(pidof easyeffects) >/dev/null; then
#            export EE_VISIBLE=true
#        fi
#    fi
    ps -aux | grep -F 'easyeffects --gapplication-service' | grep -v grep >/dev/null
    if [ $? != 0 ] ; then
        export EE_DAEMON_STATUS=false
    fi
}

# check antiX startup file for easyeffects entries.
function get_startup_status {
    if ! grep ^[[:space:]]*"${EED_ENTRY_STARTUP}" "$EED_STARTUP_FILE" >/dev/null; then
        # There no active startup entry present, either deactivated or nonexistent.
        export EED_STARTUP_STATUS=false
        if grep ^[[:space:]]*[#][[:space:]]*"${EED_ENTRY_STARTUP}"[[:space:]]*[#]*[[:space:]]* "$EED_STARTUP_FILE" >/dev/null; then
            export EED_ACTIVATE_ENTRY=true
        elif grep ^[[:space:]]*[#][#][[:space:]]*"${EED_ENTRY_STARTUP}"[[:space:]]*[#]*[[:space:]]* "$EED_STARTUP_FILE" >/dev/null; then
            # Entry is hard blocked by double sharp in config file $EED_STARTUP_FILE. Put up a warning.
            export EED_ACTIVATE_ENTRY=true
            export EED_HARD_BLOCKED=true
        else
            # There is still no entry.
            export EED_ADD_ENTRY=true
        fi
    else
        # There is an active entry, maybe an additional deactivated entry also.
        export EED_STARTUP_STATUS=true
        if grep ^[[:space:]]*[#][[:space:]]*"${EED_ENTRY_STARTUP}"[[:space:]]*[#]*[[:space:]]* "$EED_STARTUP_FILE" >/dev/null || grep ^[[:space:]]*[#][#][[:space:]]*"${EED_ENTRY_STARTUP}"[[:space:]]*[#]*[[:space:]]* "$EED_STARTUP_FILE" >/dev/null; then
            export EED_REMOVE_ENTRY=true
        else
            # There is already an additional disabled entry present. So we'll remove the active one bluntly.
            export EED_DISABLE_ENTRY=true
        fi 
    fi
}

# add or remove entries, depending on findings.
function toggle_startup {
    if $EED_ACTIVATE_ENTRY; then
        # show warning about hard blocked entries, ask user for consent to activate them anyway.
        if EED_HARD_BLOCKED; then
            :   # something in here
        fi
        # remove sharp sign to uncomment
        sed -i "s/^[[:space:]]*#[[:space:]]*\($EED_ENTRY_STARTUP.*\)$/\1/" "$EED_STARTUP_FILE"
    elif $EED_ADD_ENTRY; then
        # append entry
        echo -e "\n$EED_ENTRY_COMMENT\n$EED_ENTRY_STARTUP" >> "$EED_STARTUP_FILE"
    elif $EED_DISABLE_ENTRY; then
        # add sharp sign to comment out
        sed -i "s/^[[:space:]]*\($EED_ENTRY_STARTUP.*\)$/# \1/" "$EED_STARTUP_FILE"
    elif $EED_REMOVE_ENTRY; then
        remove duplicate entry.
        sed -i "/^[[:space:]]*$EED_ENTRY_STARTUP.*$/d" "$EED_STARTUP_FILE"
    fi
}

# export functions in need to be started from a child shell process
export -f toggle_daemon toggle_startup

# close former instance on restart loop
pkill -f "$(eval_gettext 'antiX easyeffects service daemon toggle')"

# fill variables
get_status
get_startup_status

# prepare dialog
if $EE_DAEMON_STATUS; then
    tooltip_01="$(eval_gettext 'Easyeffects equaliser is running in service daemon mode. Will be stopped when switch is flipped. Any GUI instance of easyeffects will be shut down the same time.')"
    switch_01="/usr/share/pixmaps/on.png"
else
    tooltip_01="$(eval_gettext 'Easyeffects equaliser is not running in service daemon mode. Will be started when switch is flipped. Any GUI instance of Easyeffects will be reinitialised.')"
    switch_01="/usr/share/pixmaps/off.png"
fi
flip_switch_01_text=" ""$(eval_gettext 'Easyeffects service daemon mode')"
if $EED_STARTUP_STATUS; then
    tooltip_02="$(eval_gettext 'Easyeffects equaliser is set to start it’s daemonised service mode on antiX startup. Flip switch to disable startup config entry.')"
    switch_02="/usr/share/pixmaps/on.png"
else
    tooltip_02="$(eval_gettext 'Easyeffects equaliser is disabled or not present in antiX startup configuration file. Flip switch to add or change config entry.')"
    switch_02="/usr/share/pixmaps/off.png"
fi
flip_switch_02_text=" ""$(eval_gettext 'Easyeffects antiX startup config     ')"

# bring up dialog; field buttons contain a restart command, forming a loop.
yad --undecorated --center --borders=10 --width=250 \
    --window-icon=/usr/share/icons/antix-papirus/easyeffects-toggle.png \
    --title="$(eval_gettext 'antiX easyeffects service daemon toggle')" \
    --form --columns=1 \
    --field="$flip_switch_01_text"!"$switch_01"!"$tooltip_01":BTN "bash -c 'toggle_daemon; coproc antiX-equaliser-toggle; exit'" \
    --field="$flip_switch_02_text"!"$switch_02"!"$tooltip_02":BTN "bash -c 'toggle_startup; coproc antiX-equaliser-toggle; exit'" \
    --button="$(eval_gettext 'Done')"!!"$(eval_gettext 'Leaves this window. On leaving (even when pressing ESC button), the changes made will be kept last state, and have been applied the moment you’ve flipped one of the switches.')":1
