#!/usr/bin/env bash
# bifrost — ephemeral file bridge: this terminal <-> your phone, via QR.
#
#   bifrost <path>            send a file TO your phone   (QR -> download, works once)
#   bifrost --get [path]      receive a file FROM your phone (QR -> upload page);
#                             path = target file or directory (default: .)
#
# Password: $DUZIE_SCRATCH_AUTH (same as the scratchpad), else a hidden prompt.
# Needs nothing but bash 3.2+ and curl. Run it anywhere:
#   curl -fsSL https://scratch.duz.ie/bifrost | bash -s -- ./file.txt
set -euo pipefail

BASE="https://bifrost.duz.ie"
API="$BASE/dev-api/bifrost"

usage() {
  cat <<'USAGE'
usage: bifrost <path>            send a file TO your phone (QR -> download, works once)
       bifrost --get [path]      receive a file FROM your phone (QR -> upload page)
options:
  --ttl <seconds>   link lifetime (default 30 min)
  --force           overwrite an existing file on --get
  --light           QR for a light-background terminal
  --no-copy         don't copy the URL to the clipboard
  -h, --help        this help
USAGE
}

die() { echo "bifrost: $*" >&2; exit 1; }

human() { awk -v s="$1" 'BEGIN{split("B KB MB GB TB",u," ");i=1;while(s>=1024&&i<5){s/=1024;i++}printf "%.1f %s",s,u[i]}'; }

# ---------------------------------------------------------------- args
MODE=send; DEST=""; TTL=""; FORCE=0; LIGHT=0; COPY=1
while [[ $# -gt 0 ]]; do
  case "$1" in
    --get|-g)      MODE=recv ;;
    --ttl|-t)      [[ $# -ge 2 ]] || die "--ttl needs a value"; TTL="$2"; shift ;;
    --force|-f)    FORCE=1 ;;
    --light)       LIGHT=1 ;;
    --no-copy)     COPY=0 ;;
    -h|--help)     usage; exit 0 ;;
    --)            shift; break ;;
    -*)            die "unknown option: $1 (see --help)" ;;
    *)             break ;;
  esac
  shift
done
[[ $# -le 1 ]] || die "one path only (see --help)"
DEST="${1:-}"

# ---------------------------------------------------------------- auth
if [[ -n "${DUZIE_SCRATCH_AUTH:-}" ]]; then
  PASSWORD="$DUZIE_SCRATCH_AUTH"
else
  read -rsp "Password: " PASSWORD </dev/tty || die "no password given"; echo
fi
AUTH=(-H "X-Auth-Password: $PASSWORD" -H "Accept: text/plain")
HDR=()
[[ -n "$TTL" ]] && HDR=(-H "X-TTL: $TTL")
[[ "$LIGHT" -eq 1 ]] && AUTH+=(-H "X-QR-Polarity: light")

# ---------------------------------------------------------------- clipboard
# Same ladder as the scratchpad bootstrap: OSC 52 reaches the terminal in
# front of you when SSH'd in; otherwise a native tool.
_osc52() { printf '\033]52;c;%s\a' "$(base64 | tr -d '\n')"; }
clip_out() {
  if   [[ -n "${SSH_TTY:-}" ]]; then _osc52
  elif command -v pbcopy  >/dev/null 2>&1; then pbcopy
  elif command -v wl-copy >/dev/null 2>&1; then wl-copy
  elif command -v xclip   >/dev/null 2>&1; then xclip -selection clipboard -in
  elif command -v xsel    >/dev/null 2>&1; then xsel --clipboard --input
  else return 1
  fi
}

# ---------------------------------------------------------------- api helpers
# api METHOD URL [curl args...]  ->  REPLY (body) and CODE (HTTP status)
api() {
  local method=$1 url=$2 out rc; shift 2
  out=$(curl -sS -X "$method" "${AUTH[@]}" "$@" -w $'\n__CODE__%{http_code}' "$url") && rc=0 || rc=$?
  [[ $rc -eq 130 || $rc -eq 143 ]] && exit "$rc"      # interrupted: the EXIT trap cleans up the slot
  [[ $rc -eq 0 ]] || die "cannot reach $BASE (curl exit $rc)"
  CODE=${out##*__CODE__}; REPLY=${out%__CODE__*}; REPLY=${REPLY%$'\n'}
}
field()    { printf '%s\n' "$REPLY" | sed -n "s/^$1=//p" | head -n 1; }
qr_block() { printf '%s\n' "$REPLY" | sed -n '/^qr=$/,$p' | tail -n +2; }

show_qr() {                                    # $1 = url
  echo; qr_block; echo
  echo "   $1"
  if [[ "$COPY" -eq 1 ]]; then
    if clip_out <<<"$1" 2>/dev/null; then echo "   (URL copied to clipboard)"
    else echo "   (clipboard unavailable)"; fi
  fi
  echo
}

# ---------------------------------------------------------------- lifecycle
ID=""; STATE=waiting; EXPIRES_IN=0; T0=$SECONDS
cleanup() {
  local rc=$?
  if [[ -n "$ID" && "$STATE" == waiting ]]; then
    if curl -sS -X DELETE "${AUTH[@]}" --max-time 15 "$API/slot/$ID" >/dev/null 2>&1; then
      echo "cancelled — link deleted" >&2
    else
      echo "WARNING: could not delete slot $ID (it expires in ${EXPIRES_IN}s)" >&2
    fi
  fi
  exit "$rc"
}
trap cleanup EXIT
trap 'echo; exit 130' INT TERM

wait_for() {                                   # sets STATE once it leaves waiting
  local remaining
  while :; do
    api GET "$API/slot/$ID/wait" --max-time 45
    [[ "$CODE" == 200 ]] || { STATE=gone; return; }
    STATE=$(field state)
    [[ "$STATE" != waiting ]] && return
    remaining=$(( EXPIRES_IN - (SECONDS - T0) )); (( remaining < 0 )) && remaining=0
    printf '\r  waiting… %02d:%02d  (Ctrl-C cancels)   ' $((remaining/60)) $((remaining%60))
  done
}

# ---------------------------------------------------------------- send
if [[ "$MODE" == send ]]; then
  FILE="$DEST"
  [[ -n "$FILE" ]] || { usage; exit 2; }
  [[ -f "$FILE" ]] || die "not a regular file: $FILE"
  NAME="${FILE##*/}"
  SIZE=$(stat -c %s "$FILE" 2>/dev/null || stat -f %z "$FILE")
  echo "⮆ $NAME  $(human "$SIZE")  — uploading…"
  api POST "$API/send" "${HDR[@]+${HDR[@]}}" -H "X-Filename: $NAME" -H "Expect:" --data-binary "@$FILE"
  [[ "$CODE" == 200 ]] || die "upload failed (HTTP $CODE) $(field error)"
  ID=$(field id); URL=$(field url); EXPIRES_IN=$(field expires_in)
  echo "⮆ scan on your phone — the link works once:"
  show_qr "$URL"
  wait_for
  case "$STATE" in
    served)  echo "✓ downloaded by your phone — file deleted from the server." ;;
    expired) echo "✗ the link expired before it was scanned — file deleted." ;;
    gone)    echo "✗ the slot is gone (deleted or expired)." ;;
    *)       echo "· state: $STATE" ;;
  esac

# ---------------------------------------------------------------- recv
else
  api POST "$API/recv" "${HDR[@]+${HDR[@]}}"
  [[ "$CODE" == 200 ]] || die "could not create the upload slot (HTTP $CODE) $(field error)"
  ID=$(field id); URL=$(field url); EXPIRES_IN=$(field expires_in)
  echo "⮇ scan on your phone to upload a file:"
  show_qr "$URL"
  wait_for
  [[ "$STATE" == uploaded ]] || die "no upload arrived (state: $STATE)"
  NAME=$(field name); SIZE=$(field size)
  if [[ -z "$DEST" || -d "$DEST" ]]; then OUT="${DEST:-.}/$NAME"; else OUT="$DEST"; fi
  if [[ -e "$OUT" && "$FORCE" -eq 0 ]]; then
    die "refuses to overwrite existing $OUT (use --force). The upload stays on the server until the link expires."
  fi
  api GET "$API/slot/$ID/data" -o "$OUT"
  [[ "$CODE" == 200 ]] || die "download failed (HTTP $CODE) $(field error)"
  echo "✓ saved $OUT  ($(human "$SIZE"))"
fi
