#!/bin/bash

if (($# == 0)); then
  echo "Usage: omarchy-cmd-share [clipboard|file|folder|picture|video]"
  exit 1
fi

MODE="$1"
shift

if [[ $MODE == "clipboard" ]]; then
  # Save clipboard content to a temporary text file
  TEMP_FILE=$(mktemp --suffix=.txt)
  wl-paste >"$TEMP_FILE"
  FILES="$TEMP_FILE"

elif [[ $MODE == "picture" ]]; then
  # Pick the most recent image from ~/Pictures
  LAST_PICTURE=$(find "$HOME/Pictures" -maxdepth 1 -type f \( -iname "*.png" -o -iname "*.jpg" -o -iname "*.jpeg" \) -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -n 1 | cut -d' ' -f2-)
  if [[ -z "$LAST_PICTURE" ]]; then
    echo "No .png/.jpg found in ~/Pictures"
    exit 1
  fi
  FILES="$LAST_PICTURE"

elif [[ $MODE == "video" ]]; then
  # Pick the most recent .mp4 video from ~/Videos
  LAST_VIDEO=$(find "$HOME/Videos" -maxdepth 1 -type f -iname "*.mp4" -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -n 1 | cut -d' ' -f2-)
  if [[ -z "$LAST_VIDEO" ]]; then
    echo "No .mp4 found in ~/Videos"
    exit 1
  fi
  FILES="$LAST_VIDEO"

else
  if (($# > 0)); then
    # Use files/folders provided as arguments
    FILES="$*"
  else
    if [[ $MODE == "folder" ]]; then
      # Pick a single folder from home directory
      FILES=$(find "$HOME" -type d 2>/dev/null | fzf)
    else
      # Pick one or more files from home directory
      FILES=$(find "$HOME" -type f 2>/dev/null | fzf --multi)
    fi
    [ -z "$FILES" ] && exit 0
  fi
fi

# Run LocalSend in its own systemd service (detached from terminal)
# Convert newline-separated files to space-separated arguments
if [[ $MODE != "clipboard" ]] && echo "$FILES" | grep -q $'\n'; then
  # Multiple files selected - convert newlines to array
  readarray -t FILE_ARRAY <<<"$FILES"
  systemd-run --user --quiet --collect localsend --headless send "${FILE_ARRAY[@]}"
else
  # Single file or clipboard mode
  systemd-run --user --quiet --collect localsend --headless send "$FILES"
fi

# Note: Temporary file will remain until system cleanup for clipboard mode
# This ensures the file content is available for the LocalSend GUI

exit 0
