#!/usr/bin/env bash
set -euo pipefail

LOG_DIR="$HOME/.local/state/swiftshare"
mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/screenshot.log"

APP_CLASS="$(hyprctl activewindow -j 2>/dev/null | jq -r '.class // .initialClass // empty' 2>/dev/null || true)"
APP_CLASS="${APP_CLASS%% *}"
APP_CLASS="${APP_CLASS//[^A-Za-z0-9]/}"
APP_CLASS="${APP_CLASS,,}"
if [ -z "$APP_CLASS" ]; then
  APP_CLASS="screenshot"
fi

GEOM="$(slurp)"
SLURP_EXIT=$?

if [ "$SLURP_EXIT" -ne 0 ] || [ -z "$GEOM" ]; then
  notify-send "SwiftShare" "Capture canceled"
  {
    echo "==== $(date) ==== capture canceled (slurp exit $SLURP_EXIT, geom='$GEOM')"
  } >>"$LOG_FILE" 2>&1
  exit 0
fi

{
  echo "==== $(date) ===="
  echo "Geometry: $GEOM"
  grim -g "$GEOM" - | swappy -f - -o - | swiftshare-upload --copy-url --app-name "$APP_CLASS"
} >>"$LOG_FILE" 2>&1
