#!/usr/bin/env sh
#
# wal - wallpaper changer for macOS

set -e

IFS=$(printf ' \n\t')

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

commands:
  [d]ark          - Change wallpaper to random dark.
  [l]ight         - Change wallpaper to random light.
  [m]ode [t]oggle - Show macOS dark/light status | Toggle dark/light status.
  [p]ick          - Fuzzy select wallpaper with fzf.
  [r]andom        - Change wallpaper to random current mode.
  [s]olid         - Change wallpaper to solid color stone.
  [t]inty         - Fuzzy select image and apply tinty theme.
  [h]elp          - Print this usage information.
"
  exit 0
}

currwall="${HOME%/}/Pictures/wall.png"
basedir="${HOME%/}/.local/share/wall/"

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

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

# shellcheck disable=SC2310
toggle() {
  if dark_mode; then
    light
  else
    dark
  fi
  status
}

# os_dark_mode=$(2>/dev/null defaults read -g AppleInterfaceStyle >/dev/null && echo "true" || echo "false")

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

# shellcheck disable=SC2310
status() {
  if dark_mode; then
    echo "theme: Dark"
  else
    echo "theme: Light"
  fi
}

osx_theme() {
  case ${subcommand} in
    s | status)
      status
      ;;
    t | toggle)
      toggle
      ;;
    *)
      status
      ;;
  esac
}

osx_wall() {
  sqlite3 ~/Library/Application\ Support/Dock/desktoppicture.db \
    "update data set value = '~/Pictures/'" && killall Dock
}

set_wallpaper() {
  osascript -e "tell application \"System Events\" to tell every desktop to set picture to \"${1}\" as POSIX file"
}

osx_wallpaper() {
  osascript -e "tell application \"System Events\" to tell every desktop to set picture to \"${1}\" as POSIX file"
}

# shellcheck disable=SC2250
osx_wallpaper_desktop() {
  path="$1"
  osascript -e 'tell application "Finder" to set desktop picture to POSIX file "'"$path"'"'
}

osx_wallpaper_current() {
  osascript -e "tell application \"Finder\"
    set wall to desktop picture as alias
    set wallpath to POSIX path of wall
  end tell"
}

info() {
  printf '%s\n' "setting wallpaper as $1"
}

img_basename() {
  dir=${1%"${1##*[!/]}"}
  dir=${dir##*/}
  dir=${dir%"$2"}
  printf '%s\n' "${dir:-/}"
}

set_bg() {
  img_short="$(img_basename "$1")"
  info "${img_short}"
  osx_wallpaper_desktop "$1"
}

set_wp() {
  rm -- "${currwall}"
  cp -- "${image}" "${currwall}"
  set_bg "${image}"
}

# lines="$(stty size | awk '{ print $1 }')"
# cols="$(stty size | awk '{ print $2 }')"

fzf_wp() {
  image=$(
    find "${basedir}" -type f | fzf --multi --delimiter='/' --with-nth='-2..' \
      --layout=reverse-list --margin=0,10,0,0 \
      --preview-window='nohidden:noborder:left:55' \
      --preview='chafa --format symbols --view-size 50x {}'
  )

  if [ -f "${image}" ]; then
    rm -- "${currwall}"
    cp -- "${image}" "${currwall}"
    set_bg "${image}"
    exit 0
  else
    exit 1
  fi
}

fzf_tinty() {
  image=$(
    find "${basedir}" -type f | fzf --multi --delimiter='/' --with-nth='-2..' \
      --layout=reverse-list --margin=0,10,0,0 \
      --preview-window='nohidden:noborder:left:55' \
      --preview='chafa --format symbols {}'
  )

  if [ -f "${image}" ]; then
    tintyname=$(basename "${image}" | awk '{ gsub(/[\. ]/, "-"); print }')
    # tintyname=$(echo "${image}" \
    #   | awk '{l=split($0, A, /\//); gsub(/[\. ]/, "-", A[l]); print A[l] }')

    rm -- "${currwall}"
    cp -- "${image}" "${currwall}"
    set_bg "${image}"

    if [ -z "${base_sys}" ]; then
      base_sys="base16"
    else
      base_sys="base24"
    fi

    tinty generate-scheme --name "${tintyname}" --slug "${tintyname}" \
      --system "${base_sys}" --variant dark --save "${image}"
    tinty apply "${base_sys}-${tintyname}"

    # tinty_gendir="${XDG_DATA_HOME-}/tinted-theming/tinty/custom-schemes/base16"
    # accentcolor=$(grep base0E "${tinty_gendir}"/${tintyname}.yaml \
    #   | awk '{ print $2 }' | sed "s|'||")
    # magick "${image}" -blur "50x30" "${blurwall-}"
    exit 0
  else
    exit 1
  fi
}

wp_random() {
  # shellcheck disable=SC2310
  if dark_mode; then
    randpic="$(find "${HOME%/}/.local/share/wall/dark" \
      | grep -E '.(png|jpg|jpeg)$' | shuf -n 1)"
    image=${randpic}
    set_wp
  else
    randpic="$(find "${HOME%/}/.local/share/wall/light" \
      | grep -E '.(png|jpg|jpeg)$' | shuf -n 1)"
    image=${randpic}
    set_wp
  fi
}

pick_random() {
  mode="$(status)"
  image="$(find "${HOME%/}/.local/share/wall/${mode}" \
    | grep -E '.(png|jpg|jpeg)$' | shuf -n 1)"
  set_wp
}

osx_solid() {
  osascript -e 'tell application "Finder" to set desktop picture to POSIX file "/System/Library/Desktop Pictures/Solid Colors/Stone.png"'
}

main() {
  case "$1" in
    d | dark)
      mode=dark
      image="$(find "${HOME%/}/.local/share/wall/dark" \
        | grep -E '.(png|jpg|jpeg)$' | shuf -n 1)"
      set_wp
      ;;
    l | light)
      mode=light
      image="$(find "${HOME%/}/.local/share/wall/light" \
        | grep -E '.(png|jpg|jpeg)$' | shuf -n 1)"
      set_wp
      ;;
    m | mode)
      subcommand="$2"
      osx_theme
      ;;
    p | pick)
      fzf_wp
      ;;
    r | random)
      wp_random
      ;;
    s | solid)
      osx_solid
      ;;
    t | tinty)
      fzf_tinty
      ;;
    h | help)
      usage
      ;;
    *)
      printf '%s\n' "${0##*/}: [dark | light | mode | pick | random | solid]" >&2
      exit 1
      ;;
  esac
}

os=$(uname -s | tr '[:upper:]' '[:lower:]')

if [ "${os}" = "darwin" ]; then
  main "$@"
else
  printf '%s\n' "${os} unknown"
  exit 1
fi
