#!/usr/bin/env bash

screenshot_dir="$HOME/Pictures/Screenshots"
remote_target="mac-attio:~/screenshot.png"
timeout=3  # seconds

notify() {
  DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$(id -u)/bus" \
  XDG_RUNTIME_DIR="/run/user/$(id -u)" \
  notify-send "$@"
}

# Record existing files
shopt -s nullglob
existing_files=("$screenshot_dir"/*.png)
existing_count=${#existing_files[@]}

# Take screenshot
niri msg action screenshot

# Wait for new file (timeout in 0.1s intervals)
deadline=$((timeout * 10))
count=0

while (( count < deadline )); do
  files=("$screenshot_dir"/*.png)
  if (( ${#files[@]} > existing_count )); then
    break
  fi
  sleep 0.1
  ((count++))
done

# Check if a new file appeared
if (( ${#files[@]} <= existing_count )); then
  exit 0  # Canceled or failed, silent exit
fi

# Get the new file (most recent)
latest_file=$(ls -1t "${files[@]}" | head -n 1)

# Small delay to ensure file is fully written
sleep 0.1

# Upload
if scp -q "$latest_file" "$remote_target"; then
  notify "Screenshot" "Uploaded to Mac"
fi
