#!/bin/sh

SETTINGS_DIR=~/.config/kali-HiDPI/
DESKTOP="$XDG_CURRENT_DESKTOP"

case "$DESKTOP" in
  XFCE)
    ;;
  *)
    echo 'ERROR: HiDPI mode only works on Xfce desktop' >&2
    notify-send -i dialog-warning 'ERROR: HiDPI mode only works on Xfce desktop'
    exit 1
    ;;
esac

mkdir -p "$SETTINGS_DIR"
grep -q "$SETTINGS_DIR" ~/.xsessionrc 2>/dev/null || \
  echo "[ -r ${SETTINGS_DIR}xsession-settings ] && . ${SETTINGS_DIR}xsession-settings" >> ~/.xsessionrc

enable_hidpi() {
  cat > "${SETTINGS_DIR}xsession-settings" <<-EOF
	export QT_SCALE_FACTOR=2
	export XCURSOR_SIZE=48
	export GDK_SCALE=2
	EOF
  . "${SETTINGS_DIR}xsession-settings"
  current_theme="$(xfconf-query -c xfwm4 -p /general/theme)"
  if echo "$current_theme" | grep Kali; then
    xfconf-query -c xfwm4 -p /general/theme -s "${current_theme}-xHiDPI"
  else
    xfconf-query -c xfwm4 -p /general/theme -s Kali-Dark-xHiDPI
  fi
  xfconf-query -c xsettings -p /Gdk/WindowScalingFactor -n -t 'int' -s 2
}

disable_hidpi() {
  export QT_SCALE_FACTOR=1
  export XCURSOR_SIZE=
  export GDK_SCALE=1
  rm "${SETTINGS_DIR}xsession-settings"
  current_theme="$(xfconf-query -c xfwm4 -p /general/theme)"
  if echo "$current_theme" | grep Kali; then
    xfconf-query -c xfwm4 -p /general/theme -s "$(echo "$current_theme" | sed 's/-xHiDPI//')"
  else
    xfconf-query -c xfwm4 -p /general/theme -s Kali-Dark
  fi
  xfconf-query -c xsettings -p /Gdk/WindowScalingFactor -s 1
}

toggle_hidpi() {
  if [ -r "${SETTINGS_DIR}xsession-settings" ]
  then
    disable_hidpi
    {
      sleep 5
      notify-send -i dialog-information 'HiDPI mode disabled'
    } &
  else
    enable_hidpi
    {
      sleep 5
      notify-send -i dialog-information 'HiDPI mode enabled'
    } &
  fi

  killall xfce4-notifyd
  killall xfsettingsd
  xfsettingsd &
  xfce4-panel -q
  xfce4-panel &
  xfdesktop -Q
  xfdesktop &
} >/dev/null 2>&1

toggle_hidpi
zenity --question --title='HiDPI mode' --text 'Do you want to keep this window-scaling mode?' --timeout=15 --width=200 || \
  toggle_hidpi

