#!/usr/bin/env bash

set -euo pipefail

theme="${KANAGAWA_THEME:-wave}"
font_size="${WEZTERM_FONT_SIZE:-13}"
window_opacity="${WEZTERM_WINDOW_OPACITY:-0.9}"
text_opacity="${WEZTERM_TEXT_OPACITY:-1.0}"
state_dir="$HOME/.cache/dotfiles"

case "$theme" in
  wave | kanagawa-wave) theme=wave ;;
  dragon | kanagawa-dragon) theme=dragon ;;
  *) theme=dragon ;;
esac

for value in "$font_size" "$window_opacity" "$text_opacity"; do
  [[ $value =~ ^([0-9]+([.][0-9]*)?|[.][0-9]+)$ ]] || {
    printf 'Invalid numeric theme value: %s\n' "$value" >&2
    exit 1
  }
done

mkdir -p "$state_dir"

write_if_changed() {
  local destination="$1" content="$2" temporary

  if [[ -f $destination ]] && [[ $(<"$destination") == "$content" ]]; then
    return
  fi

  temporary="$(mktemp "$state_dir/.theme.XXXXXX")"
  printf '%s\n' "$content" >"$temporary"
  mv "$temporary" "$destination"
}

write_if_changed "$state_dir/tmux-theme.conf" \
  "source-file \"$HOME/.config/tmux/$theme-theme.conf\""

write_if_changed "$state_dir/wezterm-env.lua" "return {
  theme = \"$theme\",
  font_size = $font_size,
  window_opacity = $window_opacity,
  text_opacity = $text_opacity,
}"
