#!/bin/bash

HOOKS_PATH=~/scripts/theme/hooks
CURRENT_THEME="light"

check_gnome_theme() {
  gsettings get org.gnome.desktop.interface gtk-theme | grep -i "dark" > /dev/null
  if [ $? -eq 0 ]; then
    echo "dark"
  else
    echo "light"
  fi
}

check_macos_theme() {
  osascript -e 'tell application "System Events" to tell appearance preferences to return dark mode' | grep -i "true" > /dev/null
  if [ $? -eq 0 ]; then
    echo "dark"
  else
    echo "light"
  fi
}

while true; do
  if [ "$(uname)" == "Darwin" ]; then
    NEW_THEME=$(check_macos_theme)
  elif [ "$(uname)" == "Linux" ]; then
    NEW_THEME=$(check_gnome_theme)
  else
    echo "Unsupported OS" 
    exit
  fi

  if [ $NEW_THEME != $CURRENT_THEME ]; then
    echo "$NEW_THEME" > ~/theme
    for hook in "$HOOKS_PATH"/*.sh; do
      echo "changing theme: $hook"
      bash -c "$hook $CURRENT_THEME $NEW_THEME" &
    done
  fi

  CURRENT_THEME=$NEW_THEME
  sleep 1
done
