#!/bin/bash
# lazzy-serve — serve a local file as a one-time download URL for the user.
#
# Uploads the file to lazzy.chat and returns a public download URL.
# The URL is valid for TTL minutes (default: 60). After expiry, the file is deleted.
#
# Usage:
#   lazzy-serve /path/to/file.zip          → 60-min download link
#   lazzy-serve /path/to/file.zip --ttl 30 → 30-min link
#   lazzy-serve /path/to/file.zip --ttl 1440 → 24-hour link

set -euo pipefail

read_env() {
  systemctl show willd-agent.service -p Environment --value 2>/dev/null \
    | tr ' ' '\n' \
    | sed -n "s/^${1}=//p" \
    | head -1
}

LAZZY_PUBLIC_URL="${LAZZY_PUBLIC_URL:-$(read_env LAZZY_PUBLIC_URL)}"
SERVICE_ID="${WILLD_SERVICE_ID:-$(read_env WILLD_SERVICE_ID)}"
AGENT_TOKEN="${WILLD_AGENT_TOKEN:-$(read_env WILLD_AGENT_TOKEN)}"

if [ -z "${LAZZY_PUBLIC_URL}" ] || [ -z "${SERVICE_ID}" ]; then
  echo "lazzy-serve: LAZZY_PUBLIC_URL or WILLD_SERVICE_ID missing — is willd-agent configured?" >&2
  exit 1
fi

file_path=""
ttl_minutes=60

while [ $# -gt 0 ]; do
  case "$1" in
    --ttl) shift; ttl_minutes="$1" ;;
    --version|-v)
      echo "lazzy-serve 1.0.0"
      exit 0
      ;;
    -h|--help|help)
      sed -n '2,15p' "$0" | sed 's/^# \?//'
      exit 0
      ;;
    --*) echo "lazzy-serve: unknown flag '$1'" >&2; exit 2 ;;
    *) file_path="$1" ;;
  esac
  shift
done

if [ -z "$file_path" ]; then
  echo "lazzy-serve: file path required" >&2
  echo "Usage: lazzy-serve /path/to/file [--ttl minutes]" >&2
  exit 1
fi

if [ ! -f "$file_path" ]; then
  echo "lazzy-serve: file not found: $file_path" >&2
  exit 1
fi

file_size=$(stat -c%s "$file_path" 2>/dev/null || stat -f%z "$file_path" 2>/dev/null || echo "?")
filename=$(basename "$file_path")

echo "📤 업로드 중: ${filename} (${file_size} bytes)..." >&2

resp=$(curl -fsS --max-time 600 -X POST \
  -H "X-Service-Id: ${SERVICE_ID}" \
  -H "Authorization: Bearer ${AGENT_TOKEN}" \
  -F "file=@${file_path};filename=${filename}" \
  -F "ttl=${ttl_minutes}" \
  "${LAZZY_PUBLIC_URL}/api/agent/serve-file") || {
    echo "lazzy-serve: upload to lazzy.chat failed" >&2
    exit 1
  }

if command -v jq >/dev/null 2>&1; then
  url=$(echo "$resp" | jq -r .url)
  expires=$(echo "$resp" | jq -r .expiresAt)
  size=$(echo "$resp" | jq -r .size)
  size_mb=$(echo "scale=1; $size/1048576" | bc 2>/dev/null || echo "?")
  expire_time=$(date -d "@${expires}" '+%H:%M' 2>/dev/null || date -r "${expires}" '+%H:%M' 2>/dev/null || echo "")
  echo "🔗 ${url}"
  echo "   ⏱ ${ttl_minutes}분 유효${expire_time:+ (${expire_time}까지)}"
  echo "   📦 ${size_mb}MB"
  echo ""
  echo "이 링크를 유저한테 보내주세요 — 클릭하면 바로 다운로드."
else
  echo "$resp"
fi
