#!/bin/bash

# GPL v.3
# Copyright 2024, 2025 antiX community, anticapitalista.
# Written 1/2024 by Robin.antiX
# Version 0.6

TEXTDOMAINDIR=/usr/share/locale
TEXTDOMAIN=antiX-acoustic-colours

# check whether we are running and bring our window up, then leave in this case.
if [ "$(wmctrl -l | sed -n 's/^\(..*\)  ..* '$"antiX acoustic colours"'/\1/p')" != "" ]; then
  wmctrl -F -a $"antiX acoustic colours"
  exit 0
fi

# declare variables
aac_lib="/etc/skel/.config/easyeffects"  # default config from which missing files in users individual config can get restored
aac_config="$XDG_CONFIG_HOME/antiX-acoustic-colours"   # inidvidual config in user's home
last_state="" # variable takes last state of acoustic colours setting
easyeffects_running=false  # variable to take previous state of easyeffects
easyeffects_visible=false  # variable to take previous state of easyeffects
export fifo_warteschlange_01="/dev/shm/antiX_acoustic_colours_fifo"

# prepare commnication between button commands and yad UI
mkfifo "$fifo_warteschlange_01"
exec 3<> $fifo_warteschlange_01

# create private config dir in user's home if not present already
mkdir -p "$aac_config"

# provide function to check for existing files and move them aside before copying the ones we need from aac_lib
function file_check () {
    private="$XDG_CONFIG_HOME"'/'"${1#/etc/skel/.config}"
    [ -f "$private" ] && mv "$private" "$private"'.bak'
    mkdir -p "${private%/*}"
    cp "$1" "${private%/*}"
}

# provide function to check for mising files and restore them from aac_lib
function file_renew () {
    private="$XDG_CONFIG_HOME"'/'"${1#/etc/skel/.config}"
    if [ ! -f "$private" ]; then
        mkdir -p "${private%/*}"
        cp "$1" "${private%/*}"
    fi
}

# provide full set of button commands
function apply_colour {
if test $1 -eq 1; then echo '@disabled@' >> "$fifo_warteschlange_01"; (easyeffects -l 'Bass Boosted' &); else echo "bash -c 'apply_colour 1'" >> "$fifo_warteschlange_01"; fi
if test $1 -eq 5; then echo '@disabled@' >> "$fifo_warteschlange_01"; (easyeffects -l 'Advanced Auto Gain' &); else echo "bash -c 'apply_colour 5'" >> "$fifo_warteschlange_01"; fi
if test $1 -eq 6; then echo '@disabled@' >> "$fifo_warteschlange_01"; (easyeffects -l 'Advanced Auto Gain + Loudness Compensation' &); else echo "bash -c 'apply_colour 6'" >> "$fifo_warteschlange_01"; fi
if test $1 -eq 2; then echo '@disabled@' >> "$fifo_warteschlange_01"; (easyeffects -l 'Treble (thin)' &); else echo "bash -c 'apply_colour 2'" >> "$fifo_warteschlange_01"; fi
if test $1 -eq 3; then echo '@disabled@' >> "$fifo_warteschlange_01"; (easyeffects -l 'Tenor Boosted' &); else echo "bash -c 'apply_colour 3'" >> "$fifo_warteschlange_01"; fi
if test $1 -eq 7; then echo '@disabled@' >> "$fifo_warteschlange_01"; (easyeffects -l 'Cathedral' &); else echo "bash -c 'apply_colour 7'" >> "$fifo_warteschlange_01"; fi
if test $1 -eq 4; then echo '@disabled@' >> "$fifo_warteschlange_01"; (easyeffects -l 'Speech Intelligibility 2' &); else echo "bash -c 'apply_colour 4'" >> "$fifo_warteschlange_01"; fi
if test $1 -eq 8; then echo '@disabled@' >> "$fifo_warteschlange_01"; (easyeffects -l 'Muffled' &); else echo "bash -c 'apply_colour 8'" >> "$fifo_warteschlange_01"; fi
echo "wmctrl -F -c \""$"antiX acoustic colours""\""  >> "$fifo_warteschlange_01"
if test $1 -eq 9; then echo '@disabled@' >> "$fifo_warteschlange_01"; (easyeffects -l 'Limiter only' &); else echo "bash -c 'apply_colour 9'" >> "$fifo_warteschlange_01"; fi
}
export -f apply_colour

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

# Depending on whether this is a first run check for missing files or copy all files over from aac_lib
if [ ! -f "$aac_config"/.0 ]; then
    while IFS= read -d '' i; do    # on first run copy needed files to user's home
       file_check "${i}" </dev/null
    done < <(find "$aac_lib" -name '*' -type f -print0)
    touch "$aac_config"/.0    # set flag file after setup on first run was completed.
else
    while IFS= read -d '' i; do    # on later runs check for files we need to run user has deleted
       file_renew "${i}" </dev/null
    done < <(find "$aac_lib" -name '*' -type f -print0)
fi

# make sure easyeffects is running in it's pseudo-demonised mode
if pidof easyeffects >/dev/null; then if xdotool search --onlyvisible --pid $(pidof easyeffects) >/dev/null; then easyeffects_visible=true; fi; fi
ps -aux | grep -F 'easyeffects --gapplication-service' | grep -v grep >/dev/null
if [ $? != 0 ] ; then
    if pidof easyeffects >/dev/null; then 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 ! $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
fi

# read current preset from easyeffects for display in window border
i="$(gsettings get com.github.wwmm.easyeffects last-loaded-output-preset)"
i="${i:1:-1}"
case "$i" in
    'Bass Boosted')             apply_colour 1;;
    'Treble (thin)')            apply_colour 2;;
    'Tenor Boosted')            apply_colour 3;;
    'Speech Intelligibility 2') apply_colour 4;;
    'Advanced Auto Gain')       apply_colour 5;;
    'Advanced Auto Gain + Loudness Compensation') apply_colour 6;;
    'Cathedral')   apply_colour 7;;
    'Muffled')     apply_colour 8;;
    'Limiter only')     apply_colour 9;;
     *)  apply_colour 0;;
esac;

# calculate window positon, so window doesn't come up in arbitrary positions on scereen after pressing a button.
y=$(($(xprop -root '_NET_WORKAREA' | sed -e "s/, / /g" | cut -d' ' -f6)-100)) # near lower border, own window hight must be taken into account.
x=20  # near left border
if $(wmctrl -m | grep herbstluft >/dev/null); then x=y=0; fi  # herbstluftwm must be treated separately

# start processing GUI dialog and preset switching loop
   yad --title=$"antiX acoustic colours""$last_state" \
       --height=65 --posx=$x --posy=$y --fixed \
       --window-icon=/usr/share/icons/antix-papirus/antiXac.png \
       --no-buttons --undecorated \
       --form --columns=5 --cycle-read \
       --field=$"Bass":fbtn \
       --field=$"Orchestra":fbtn \
       --field=$"Jazz":fbtn \
       --field=$"Treble":fbtn \
       --field=$"Solo":fbtn \
       --field=$"Cathedral":fbtn \
       --field=$"Speech":fbtn \
       --field=$"Muffled":fbtn \
       --field=!'/usr/share/pixmaps/tick_green18.png'!:btn \
       --field=$"Off":fbtn <&3
exec 3>&-

rm -f "$fifo_warteschlange_01"
exit 0
