#!/usr/bin/env bash
set -euo pipefail

# Static Site List - FTP directory listing helper script
# Usage: list.sh [project-name] [--config path]

# ─── Argument Parsing ───────────────────────────────────────────────

PROJECT_NAME=""
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="${SCRIPT_DIR}/static-site-deploy.yml"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --config)
      CONFIG_FILE="$2"
      shift 2
      ;;
    *)
      if [[ -z "$PROJECT_NAME" ]]; then
        PROJECT_NAME="$1"
      else
        echo "Error: unexpected argument '$1'" >&2
        exit 1
      fi
      shift
      ;;
  esac
done

# Read bot_id from environment variable
BOT_ID="${ASSISTANT_ID:-}"
if [[ -z "$BOT_ID" ]]; then
  echo "Error: ASSISTANT_ID environment variable is not set" >&2
  exit 1
fi

# ─── Config Parsing ─────────────────────────────────────────────────

if [[ ! -f "$CONFIG_FILE" ]]; then
  echo "Error: config file '$CONFIG_FILE' not found" >&2
  exit 1
fi

# Simple YAML parser (no external dependencies)
parse_yaml() {
  local key="$1"
  grep "^${key}:" "$CONFIG_FILE" | sed "s/^${key}:[[:space:]]*//" | sed 's/[[:space:]]*#.*//' | sed 's/[[:space:]]*$//' | sed 's/^[\"'\'']\(.*\)[\"'\'']$/\1/'
}

HOST=$(parse_yaml "host")
FTP_USER=$(parse_yaml "ftp_user")
FTP_PASS=$(parse_yaml "ftp_pass")
FTP_PORT=$(parse_yaml "ftp_port")
USE_FTPS=$(parse_yaml "use_ftps")
WEB_ROOT=$(parse_yaml "web_root")
DOMAIN=$(parse_yaml "domain")

# Defaults
FTP_PORT="${FTP_PORT:-21}"
USE_FTPS="${USE_FTPS:-true}"

# Validate required fields
for field in HOST FTP_USER FTP_PASS WEB_ROOT DOMAIN; do
  if [[ -z "${!field}" ]]; then
    echo "Error: missing required config field: $(echo "$field" | tr '[:upper:]' '[:lower:]')" >&2
    exit 1
  fi
done

# Determine remote path
if [[ -z "$PROJECT_NAME" ]]; then
  # List bot directory
  REMOTE_PATH="${WEB_ROOT}/${BOT_ID}"
  DISPLAY_PATH="/${BOT_ID}/"
else
  # List specific project
  REMOTE_PATH="${WEB_ROOT}/${BOT_ID}/${PROJECT_NAME}"
  DISPLAY_PATH="/${BOT_ID}/${PROJECT_NAME}/"
fi

# ─── List Files ─────────────────────────────────────────────────────

echo "=== FTP Directory Listing ==="
echo "Bot ID:      $BOT_ID"
echo "Path:        $DISPLAY_PATH"
echo "Remote:      ftp://${FTP_USER}@${HOST}:${FTP_PORT}${REMOTE_PATH}/"
echo ""

curl_ssl_flag=""
if [[ "$USE_FTPS" == "true" ]]; then
  curl_ssl_flag="--ssl-reqd"
fi

ftp_url="ftp://${FTP_USER}:${FTP_PASS}@${HOST}:${FTP_PORT}${REMOTE_PATH}/"

# List directory
listing=$(curl -s --list-only $curl_ssl_flag "$ftp_url" 2>&1)

if [[ $? -ne 0 ]]; then
  echo "Error: Failed to list directory" >&2
  echo "$listing" >&2
  exit 1
fi

# Format output
echo "$listing" | while IFS= read -r item; do
  # Skip . and ..
  if [[ "$item" == "." || "$item" == ".." ]]; then
    continue
  fi

  # Check if it's a directory by trying to list it
  if curl -s --list-only $curl_ssl_flag "${ftp_url}${item}/" >/dev/null 2>&1; then
    echo "${item}/"
  else
    echo "$item"
  fi
done

echo ""
echo "=== Listing Complete ==="
