#!/bin/bash

switcher='org.altlinux.gnome-legacy-theme-switcher'
gnome='org.gnome.desktop.interface'

get_light(){
  gsettings get $switcher variant-light
}

get_dark(){
  gsettings get $switcher variant-dark
}

write_theme_name(){
  read -r theme
  gsettings set $gnome gtk-theme "$theme"
}

theme_name_from_color(){
  read -r color
  [[ "$color" == *'dark'* ]] && get_dark || get_light
}

print_help(){
  cat << EOF
  usage: $0 <sync|daemon>

    sync   - apply current theme variant and exit
    daemon - monitor colorscheme and automatically syncronize theme variant

  gsettings configuration:

    $switcher dynamic (boolean) - enables theme syncronization for daemon mode. Disable to use a static theme.
    $switcher variant-light (string) - which gtk-theme to use when light mode activated.
    $switcher variant-dark (string) - which gtk-theme to use when dark mode activated.

  Use gnome-tweaks for easy GUI configuration.
EOF
}


if [ -z "$1" ]
then
  print_help
else
  if [ "$1" == 'sync' ]
  then
    gsettings get $gnome color-scheme | theme_name_from_color | write_theme_name
  elif [ "$1" == 'daemon' ]
  then
    gsettings get $gnome color-scheme | theme_name_from_color | write_theme_name
    gsettings monitor $gnome color-scheme | \
    while read -r color
    do
      [[ "`gsettings get $switcher dynamic`" == "true" ]] && \
        theme_name_from_color <<< "$color" | write_theme_name
    done
  else
    print_help
  fi
fi
