#!/bin/sh
set -eu

BASE="/opt/router-ops"
PUBLIC="$BASE/public"
TOKEN="$(cat "$PUBLIC/.router-public-token")"
ROOT="$PUBLIC/r/$TOKEN"

if [ $# -lt 2 ]; then
  echo "Usage: router-publish-report <label> <file1> [file2 ...]" >&2
  exit 1
fi

LABEL_RAW="$1"
shift

LABEL="$(printf '%s' "$LABEL_RAW" | tr -c 'A-Za-z0-9_.-' '_' | sed 's/__*/_/g; s/^_//; s/_$//')"
[ -n "$LABEL" ] || LABEL="report"

TS="$(date +%Y%m%d-%H%M%S)"
DIR="$ROOT/${TS}_${LABEL}"

mkdir -p "$DIR" "$ROOT/latest"
chmod 755 "$DIR" "$ROOT/latest"

REFUSE_RE='raw|\.env|secret|secrets|private|Private|id_rsa|id_ed25519|authorized_keys|wg[0-9]?.conf|amnezia|hmn.*code|access.*code'

for SRC in "$@"; do
  if [ ! -f "$SRC" ]; then
    echo "ERROR: file not found: $SRC" >&2
    exit 1
  fi

  BASESRC="$(basename "$SRC")"

  if printf '%s\n%s\n' "$SRC" "$BASESRC" | grep -Eiq "$REFUSE_RE"; then
    echo "REFUSE: suspicious path/name, not publishing: $SRC" >&2
    exit 2
  fi

  cp -a "$SRC" "$DIR/$BASESRC"
  chmod 644 "$DIR/$BASESRC"

  cp -a "$SRC" "$ROOT/latest/$BASESRC"
  chmod 644 "$ROOT/latest/$BASESRC"
done

# Folder-local index
{
  echo '<!doctype html><html><head><meta charset="utf-8"><title>router report</title></head><body>'
  echo "<h1>$TS $LABEL</h1>"
  echo '<ul>'
  find "$DIR" -maxdepth 1 -type f | sort | while read -r f; do
    b="$(basename "$f")"
    echo "<li><a href=\"$b\">$b</a></li>"
  done
  echo '</ul>'
  echo '<p><a href="../">Back to index</a></p>'
  echo '</body></html>'
} > "$DIR/index.html"
chmod 644 "$DIR/index.html"

router-public-reindex >/dev/null

LOG="$PUBLIC/cloudflared-quick.log"
TRYCF_BASE=""
if [ -f "$LOG" ]; then
  TRYCF_BASE="$(grep -Eo 'https://[-a-zA-Z0-9.]+\.trycloudflare\.com' "$LOG" | tail -n 1 || true)"
fi

echo "PUBLISHED_DIR=$DIR"
echo "LOCAL_INDEX=http://192.168.30.84:8099/r/$TOKEN/"
if [ -n "$TRYCF_BASE" ]; then
  echo "TRYCF_INDEX=$TRYCF_BASE/r/$TOKEN/"
  echo "TRYCF_REPORT=$TRYCF_BASE/r/$TOKEN/$(basename "$DIR")/"
fi
