#!/bin/sh
# File: fix-alttab
# Location: /usr/libexec/fix-alttab
# Author: bgstack15
# Startdate: 2023-07-10-2 08:10
# SPDX-License-Identifier: GPL-3.0
# Title: fix-alttab
# History:
# Usage:
#    called by fix-alttab-daemon
# Reference:
#    https://unix.stackexchange.com/questions/537529/how-do-i-get-xdg-config-home-from-a-shell-script-command-line
# Improve:
# Dependencies:
#    dep-devuan: xrandr, alttab
# Documentation: README.md

# load settings
test -z "${DEFAULTSDIR}" && DEFAULTSDIR=/etc/sysconfig
grep -qiE 'de(vu|bi)an|ubuntu|mint' /etc/os-release 1>/dev/null 2>&1 && DEFAULTSDIR=/etc/default
test -f "${DEFAULTSDIR}/fix-alttab" && . "${DEFAULTSDIR}/fix-alttab"
test -f "${XDG_CONFIG_HOME:-~/.config}/fix-alttab" && . "${XDG_CONFIG_HOME:-~/.config}/fix-alttab"
# just in case no settings defined there
test -z "${ALTTAB_COMMON}" && ALTTAB_COMMON="alttab -w 1 -theme numix-circle"
test -z "${ALTTAB_LEFTYES_RIGHTYES}" && ALTTAB_LEFTYES_RIGHTYES=""
test -z "${ALTTAB_LEFTNO_RIGHTYES}" && ALTTAB_LEFTNO_RIGHTYES="-vp 1920x1080+1920+0"
test -z "${ALTTAB_LEFTYES_RIGHTNO}" && ALTTAB_LEFTYES_RIGHTNO="" #unsupported
test -z "${ALTTAB_LEFTNO_RIGHTNO}" && ALTTAB_LEFTNO_RIGHTNO="" # unsupported

# for better security, strip out any semicolons from these values because we evaluate without quotes
_strip() {
   printf '%s' "${@}" | sed -r -e 's/;.*$//;'
}
ALTTAB_COMMON="$( _strip "${ALTTAB_COMMON}" )"
ALTTAB_LEFTYES_RIGHTYES="$( _strip "${ALTTAB_LEFTYES_RIGHTYES}" )"
ALTTAB_LEFTNO_RIGHTYES="$( _strip "${ALTTAB_LEFTNO_RIGHTYES}" )"
ALTTABLEFTYES_RIGHTNO="$( _strip "${ALTTABLEFTYES_RIGHTNO}" )"
ALTTAB_LEFTNO_RIGHTNO="$( _strip "${ALTTAB_LEFTNO_RIGHTNO}" )"

# always evaluate this
_ALTTAB_COMMAND_TO_KILL="$( echo "${ALTTAB_COMMON}" | awk '{print $1}' )"

# main
# set environment variables "left" and "right" to yes or no, to indicate if monitor is there.
unset right left
eval $( xrandr | awk 'BEGIN{a[0]="no";a[1]="yes"}/HDMI-1/{if($2~/\<connected/){r=1;}else{r=0};} /HDMI-0/{if($2~/\<connected/){l=1;}else{l=0;};} END{print "right="a[r];print "left="a[l];}' )
unset _ALTTAB_PARAMS
case "${left}${right}" in
   yesyes)
      printf '%s\n' "Using left yes, right yes"
      _ALTTAB_PARAMS="${ALTTAB_LEFTYES_RIGHTYES}"
      ;;
   noyes)
      printf '%s\n' "Using left no, right yes"
      _ALTTAB_PARAMS="${ALTTAB_LEFTNO_RIGHTYES}"
      ;;
   yesno)
      printf '%s\n' "Using left no, right yes"
      _ALTTAB_PARAMS="${ALTTAB_LEFTNO_RIGHTYES}"
      ;;
   nono)
      printf '%s\n' "Using left no, right no: UNSUPPORTED!"
      _ALTTAB_PARAMS="${ALTTAB_LEFTNO_RIGHTNO}"
      ;;
   *)
      printf '%s\n' "Unknown config: leftright \"${left}${right}\". Aborted." 1>&2 ; exit 1
      ;;
esac
test -n "${APPLY}" && {
   test -n "${DEBUG}" && set -x
   killall "${_ALTTAB_COMMAND_TO_KILL}"
   # unquoted here:
   ${ALTTAB_COMMON} ${_ALTTAB_PARAMS} &
   set +x
}
