#!/usr/bin/env bash
# macOS: already has pbcopy → works out of the box
# Wayland (Fedora, Ubuntu ≥22.04, etc.): sudo apt install wl-clipboard  or dnf install wl-clipboard
# X11:
# Preferred: sudo apt install xclip   (Debian/Ubuntu)
# Fallback: sudo apt install xsel

# clip - Copy data to clipboard from stdin or file
# Usage: clip < file.txt
#        echo "hello" | clip
#        clip file.txt
#        clip - <<< "copied from here-string"
# Detect the platform and choose the right clipboard command
if [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    clipboard_cmd="pbcopy"
elif [[ -n "$WAYLAND_DISPLAY" ]] && command -v wl-copy >/dev/null; then
    # Wayland with wl-clipboard installed
    clipboard_cmd="wl-copy"
elif [[ -n "$DISPLAY" ]] && command -v xclip >/dev/null; then
    # X11 with xclip
    clipboard_cmd="xclip -selection clipboard"
elif [[ -n "$DISPLAY" ]] && command -v xsel >/dev/null; then
    # X11 with xsel (fallback)
    clipboard_cmd="xsel --clipboard --input"
else
    echo "Error: No supported clipboard tool found." >&2
    echo "Install one of: pbcopy (macOS), wl-copy (Wayland), xclip, or xsel" >&2
    exit 1
fi

# If arguments are given, treat them as files
if [[ $# -gt 0 ]]; then
    for file in "$@"; do
        if [[ -f "$file" ]] || [[ "$file" = "-" ]]; then
            cat -- "$file" | $clipboard_cmd
        else
            echo "Error: File not found: $file" >&2
            exit 1
        fi
    done
else
    # No arguments → read from stdin
    $clipboard_cmd
fi
