#!/usr/bin/env bash
# publish — copy a file into the Ingriid Brain public web root and print its live URL.
#
# Usage:
#   publish <source-file> [dest-name]      # public  -> https://files.ingriid.ai/<dest-name>
#   publish --shared <source-file> [name]  # shared  -> https://brain.ingriid.ai/shared/<name>
#
# Handles the two recurring gotchas automatically:
#   * sets 0644 so the web server (different uid) can read the file
#   * confirms the file is in place (external curl can't work: no outbound internet)
set -euo pipefail

PUBLIC_DIR="/opt/data/public"
SHARED_DIR="/opt/data/shared"
PUBLIC_URL="https://files.ingriid.ai"
SHARED_URL="https://brain.ingriid.ai/shared"

dir="$PUBLIC_DIR"; base_url="$PUBLIC_URL"
if [[ "${1:-}" == "--shared" ]]; then
  dir="$SHARED_DIR"; base_url="$SHARED_URL"; shift
fi

src="${1:-}"
if [[ -z "$src" ]]; then
  echo "usage: publish [--shared] <source-file> [dest-name]" >&2; exit 2
fi
if [[ ! -f "$src" ]]; then
  echo "error: source file not found: $src" >&2; exit 1
fi

dest_name="${2:-$(basename "$src")}"
dest="$dir/$dest_name"

if [[ ! -w "$dir" ]]; then
  cat >&2 <<EOF
error: $dir is not writable by $(whoami).
One-time fix (run as root, persists afterwards):
  chown $(whoami) $dir    # or: chmod 0775 $dir && chgrp $(whoami) $dir
EOF
  exit 1
fi

cp "$src" "$dest"
chmod 0644 "$dest"
echo "published: $base_url/$dest_name"
echo "local:     $dest  ($(stat -c '%A %s bytes' "$dest"))"
echo "note: external curl from this container returns proxy 403 (no outbound net) — click the URL to verify."
