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

# Static Site Read - FTP file content reader
# Usage: read.sh <file-path> [--config path]

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

FILE_PATH=""
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 "$FILE_PATH" ]]; then
        FILE_PATH="$1"
      else
        echo "Error: unexpected argument '$1'" >&2
        exit 1
      fi
      shift
      ;;
  esac
done

if [[ -z "$FILE_PATH" ]]; then
  echo "Usage: read.sh <file-path> [--config path]" >&2
  echo "  file-path: project-name/path/to/file.html" >&2
  exit 1
fi

# 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")

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

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

REMOTE_PATH="${WEB_ROOT}/${BOT_ID}/${FILE_PATH}"

# ─── Read File ─────────────────────────────────────────────────────

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}"

content=$(curl -s $curl_ssl_flag "$ftp_url" 2>&1)

if [[ $? -ne 0 ]]; then
  echo "Error: Failed to read file '${FILE_PATH}'" >&2
  echo "$content" >&2
  exit 1
fi

echo "$content"
