#!/bin/bash
#
# kinja-img.com Screenshot Uploader for Flameshot
#
# Installation:
#   1. Save this script: curl -o ~/bin/kinja-upload.sh https://kinja-img.com/api/kinja-upload.sh
#   2. Make executable: chmod +x ~/bin/kinja-upload.sh
#   3. Bind to hotkey (e.g., in KDE/GNOME settings)
#
# Dependencies: flameshot, curl, jq, xclip (or wl-copy for Wayland)
#
# Usage:
#   ./kinja-upload.sh          - Interactive screenshot selection
#   ./kinja-upload.sh file.png - Upload existing file
#

API_URL="https://kinja-img.com/api/upload"

# Detect clipboard command (Wayland vs X11)
if [ "$XDG_SESSION_TYPE" = "wayland" ]; then
    CLIP_CMD="wl-copy"
else
    CLIP_CMD="xclip -selection clipboard"
fi

# Check dependencies
for cmd in curl jq; do
    if ! command -v $cmd &> /dev/null; then
        notify-send "Error" "$cmd is required but not installed" -u critical
        exit 1
    fi
done

upload_file() {
    local file="$1"

    if [ ! -f "$file" ]; then
        notify-send "Error" "File not found: $file" -u critical
        exit 1
    fi

    # Upload and get response
    response=$(curl -s -X POST -F "image=@$file" "$API_URL")

    # Check for success
    success=$(echo "$response" | jq -r '.success')

    if [ "$success" = "true" ]; then
        url=$(echo "$response" | jq -r '.url')
        echo -n "$url" | $CLIP_CMD
        notify-send "Uploaded!" "$url" -i dialog-information
        echo "$url"
    else
        error=$(echo "$response" | jq -r '.error')
        notify-send "Upload Failed" "$error" -u critical
        exit 1
    fi
}

# If file argument provided, upload it
if [ -n "$1" ]; then
    upload_file "$1"
    exit 0
fi

# Otherwise, take screenshot with Flameshot
if ! command -v flameshot &> /dev/null; then
    notify-send "Error" "Flameshot is required for screenshots" -u critical
    exit 1
fi

# Create temp file
TMPFILE=$(mktemp /tmp/screenshot-XXXXXX.png)

# Take screenshot (Flameshot saves to temp file)
flameshot gui --raw > "$TMPFILE"

# Check if screenshot was taken (file not empty)
if [ ! -s "$TMPFILE" ]; then
    rm -f "$TMPFILE"
    exit 0  # User cancelled, silent exit
fi

# Upload
upload_file "$TMPFILE"

# Cleanup
rm -f "$TMPFILE"
