#!/usr/bin/env bash
# curl reg.soon.it/cp | bash  —  fetch & run a copyparty file server in the CWD.
# Defaults to port 3923, and ALSO :80 when it can be bound (e.g. via sudo).
# Override:  curl reg.soon.it/cp | bash -s -- -p 8080 -v ./shared
#            curl reg.soon.it/cp | sudo bash           # serves :80 + :3923
set -eo pipefail

# --- locate a Python 3 interpreter -------------------------------------------
PY=""
for c in python3 python; do
  if command -v "$c" >/dev/null 2>&1 \
     && "$c" -c 'import sys; sys.exit(0 if sys.version_info[0] >= 3 else 1)' 2>/dev/null; then
    PY="$c"; break
  fi
done
if [ -z "$PY" ]; then
  echo "copyparty needs Python 3, which wasn't found. Install python3 and retry." >&2
  exit 1
fi

# --- fetch the self-contained copyparty (curl or wget); cached, weekly refresh
CACHE="${XDG_CACHE_HOME:-${HOME:-/tmp}/.cache}/copyparty"
SFX="$CACHE/copyparty-sfx.py"
URL="https://github.com/9001/copyparty/releases/latest/download/copyparty-sfx.py"
mkdir -p "$CACHE"

fetch() {  # fetch <url> <dest>
  if command -v curl >/dev/null 2>&1; then curl -fL --retry 3 -o "$2" "$1"
  elif command -v wget >/dev/null 2>&1; then wget -O "$2" "$1"
  else echo "need curl or wget to download copyparty" >&2; return 1; fi
}

stale=1
[ -s "$SFX" ] && stale=0
[ "$stale" = 0 ] && find "$SFX" -mtime +7 2>/dev/null | grep -q . && stale=1
if [ "$stale" = 1 ]; then
  echo "downloading copyparty..." >&2
  fetch "$URL" "$SFX.tmp"
  mv "$SFX.tmp" "$SFX"
fi

# --- choose default ports only if the user didn't pass -p --------------------
user_set_port=0
for a in "$@"; do
  case "$a" in -p|-p[0-9]*) user_set_port=1 ;; esac
done

if [ "$user_set_port" = 0 ]; then
  ports="3923"
  if "$PY" - <<'PY' 2>/dev/null
import socket, sys
s = socket.socket()
try:
    s.bind(("0.0.0.0", 80)); s.close()
except Exception:
    sys.exit(1)
PY
  then
    ports="80,3923"
    echo "port 80 bindable -> serving on 80 and 3923" >&2
  else
    echo "port 80 not bindable -> serving on 3923 only (rerun with sudo for :80)" >&2
  fi
  set -- -p "$ports" "$@"
fi

echo "starting copyparty in $(pwd) (Ctrl-C to stop)" >&2
exec "$PY" "$SFX" "$@"
