#!/bin/sh

usage() {
  printf %s "\
$(basename "$0")
  a simple script to toggle macOS dark/light theme

commands:
  [d]ark        - Set theme to Dark.
  [h]elp        - Display this message.
  [l]ight       - Set theme to Light.
  [s]tatus      - Get current theme.
  [t]oggle      - Toggle theme between Dark and Light.

options:
  -h, --help    - Display this message.
"
  exit 0
}

light() {
  osascript -e 'tell app "System Events" to tell appearance preferences to set dark mode to false'
}

dark() {
  osascript -e 'tell app "System Events" to tell appearance preferences to set dark mode to true'
}

toggle() {
  if dark_mode; then
    light
  else
    dark
  fi
}

dark_mode() {
  dark_mode_on=$(defaults read -g AppleInterfaceStyle 2>/dev/null)
  # dark_mode_on=$(2>/dev/null defaults read -g AppleInterfaceStyle)
  if [ "${dark_mode_on}" = "Dark" ]; then
    true
  else
    false
  fi
}

status() {
  if dark_mode; then
    printf '%s' "Dark"
  else
    printf '%s' "Light"
  fi
}

if [ "$#" -eq 0 ]; then
  status
  exit 0
fi

case "$1" in
  -h | --help)
    usage
    ;;
  d | dark)
    dark
    ;;
  h | help)
    usage
    ;;
  l | light)
    light
    ;;
  s | status)
    status
    ;;
  t | toggle)
    toggle
    ;;
  *)
    status
    ;;
esac
