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

log_file="$HOME/.cache/matugen-sync-wallpaper.log"

mkdir -p "$HOME/.cache"

{
  wallpaper_path="$(cat "$HOME/.cache/matugen-last-image")"
  if [ -n "$wallpaper_path" ]; then
    base_name="$(basename "$wallpaper_path")"
    dest_path="$HOME/.cache/matugen-wallpapers/$base_name"

    mkdir -p "$HOME/.cache/matugen-wallpapers"
    cp -f "$wallpaper_path" "$dest_path"

    ssh mac-attio "mkdir -p ~/.cache/matugen-wallpapers"
    scp "$dest_path" "mac-attio:~/.cache/matugen-wallpapers/$base_name"
    ssh mac-attio "osascript -e 'tell application \"System Events\" to tell every desktop to set picture to POSIX file \"~/.cache/matugen-wallpapers/$base_name\"'"
  fi
} >>"$log_file" 2>&1
