#!/usr/bin/env sh
set -eu

host="${MATUGEN_SYNC_HOST:-mac-attio}"
log_file="$HOME/.cache/matugen-sync-mac.log"

mkdir -p "$HOME/.cache"

usage() {
  echo "usage:" >&2
  echo "  sync-mac.sh file <source_path> <remote_path> [--remote-cmd <command>]" >&2
  echo "  sync-mac.sh wallpaper <wallpaper_path_file>" >&2
  exit 1
}

sync_file() {
  source_path="$1"
  remote_path="$2"
  remote_cmd="${3-}"

  # If caller passes a local absolute path, mirror it under remote $HOME.
  case "$remote_path" in
    "$HOME")
      remote_path="~"
      ;;
    "$HOME"/*)
      remote_path="~/${remote_path#"$HOME"/}"
      ;;
  esac

  remote_dir="$(dirname "$remote_path")"
  remote_tmp="${remote_path}.tmp"

  ssh "$host" "mkdir -p $remote_dir"
  scp "$source_path" "$host:$remote_tmp"
  ssh "$host" "mv $remote_tmp $remote_path"

  if [ -n "$remote_cmd" ]; then
    ssh "$host" "$remote_cmd"
  fi
}

sync_wallpaper() {
  wallpaper_path_file="$1"

  [ -f "$wallpaper_path_file" ] || exit 0

  wallpaper_path="$(cat "$wallpaper_path_file")"
  [ -n "$wallpaper_path" ] || exit 0
  [ -f "$wallpaper_path" ] || exit 0

  base_name="$(basename "$wallpaper_path")"
  local_cache_dir="$HOME/.cache/matugen-wallpapers"
  local_copy="$local_cache_dir/$base_name"

  mkdir -p "$local_cache_dir"
  cp -f "$wallpaper_path" "$local_copy"

  ssh "$host" "mkdir -p ~/.cache/matugen-wallpapers"
  scp "$local_copy" "$host:~/.cache/matugen-wallpapers/$base_name"
  ssh "$host" "osascript -e 'tell application \"System Events\" to tell every desktop to set picture to POSIX file \"~/.cache/matugen-wallpapers/$base_name\"'"
}

mode="${1-}"
[ -n "$mode" ] || usage
shift

{
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] mode=$mode"

  case "$mode" in
    file)
      [ "$#" -ge 2 ] || usage
      source_path="$1"
      remote_path="$2"
      shift 2

      remote_cmd=""
      if [ "${1-}" = "--remote-cmd" ]; then
        [ "$#" -eq 2 ] || usage
        remote_cmd="$2"
      elif [ "$#" -ne 0 ]; then
        usage
      fi

      sync_file "$source_path" "$remote_path" "$remote_cmd"
      ;;

    wallpaper)
      [ "$#" -eq 1 ] || usage
      sync_wallpaper "$1"
      ;;

    *)
      usage
      ;;
  esac
} >>"$log_file" 2>&1
