#!/usr/bin/env sh
# File: switch-monitors-trayicon.sh
# Location: /usr/local/bin
# Author: bgstack15
# SPDX-License-Identifier: GPL-3.0
# Startdate: 2023-12-05-3 16:29
# Title: Trayicon for switching monitor config
# Purpose: Provide easy drop-down for pcb-009 for monitor control
# History:
# Usage:
# Reference:
#    Heavily ripped keyboard-leds-trayicons
# Improve:
#    There is no loop, so manually touching the kill file does not stop the process like it should.
# Dependencies:
#    raw: mktrayicon, awk, switch-monitors.sh
#    devuan: mktrayicon, mawk | gawk, x11-xserver-utils

# CONFIG FILES
test -z "${SWITCH_MONITORS_CONF}" && SWITCH_MONITORS_CONF="${HOME}/.config/switch-monitors.conf"

# FUNCTIONS

get_conf() {
   # Ripped from framework.sh
   # call: get_conf "${conffile}"
   local _infile="$1"
   local _tmpfile1="$( mktemp )"
   sed -e 's/^\s*//;s/\s*$//;/^[#$]/d;s/\s*[^\]#.*$//;' "${_infile}" | grep -viE "^$" | while read _line ;
   do
      local _left="$( echo "${_line}" | cut -d'=' -f1 )"
      eval "_thisval=\"\${${_left}}\""
      test -z "${_thisval}" && echo "${_line}" >> "${_tmpfile1}"
   done
   test -f "${_tmpfile1}" && { . "${_tmpfile1}" 1>/dev/null 2>&1 ; }
   /bin/rm -rf "${_tmpfile1}" 1>/dev/null 2>&1
}

clean_switch_monitors_trayicon() {
   { test -e "${switch_monitors_icon}" && echo "q" > "${switch_monitors_icon}" ; } 1>/dev/null 2>&1 &
   sleep 1 && rm -f "${switch_monitors_icon}" "${SMT_KILLFILE}"
}

# LOAD CONFIGS
# order is important! The last one called gets precedence.
# instead of simply dot-sourcing the conf file, pass it to get_conf which only applies new values, so this process's environment is preserved
for thisconf in "${SMT_CONF}" "${SMT_USER_CONF}" "${SMT_GLOBAL_CONF}" ;
do
   test -r "${thisconf}" && get_conf "${thisconf}"
done

# DEFAULTS in case configs did not have these values
test -z "${SMT_ICON}" && SMT_ICON=display
test -z "${SMT_KILLFILE}" && SMT_KILLFILE="/tmp/kill-all-switch-monitors-trayicons"

# INITIALIZATION

switch_monitors_icon="/var/run/user/$( id -u )/${$}.switch_monitors.icon"

mkfifo "${switch_monitors_icon}"
mktrayicon "${switch_monitors_icon}" &
{
   echo "i ${SMT_ICON}"
   echo "t pcb-009 easy display settings"
   echo "m right,switch-monitors.sh right|both,switch-monitors.sh both|-----|quit,echo 'q' > ${switch_monitors_icon} ; touch "${SMT_KILLFILE}""
} > "${switch_monitors_icon}"

rm -f "${SMT_KILLFILE}"

trap 'trap "" 2 ; touch "${SMT_KILLFILE}" '  2 # CTRL-C
wait %1

# safety shutoff
clean_switch_monitors_trayicon
