#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
SFTP_USER="${SFTP_USER:-witmatec}"
SFTP_HOST="${SFTP_HOST:-74.220.219.141}"
REMOTE_DIR="${REMOTE_DIR:-/home1/witmatec/public_html/amipro}"
LIVE_BASE_URL="${LIVE_BASE_URL:-https://amipro.me}"

batch_file="$(mktemp)"
cleanup() {
  rm -f "$batch_file"
}
trap cleanup EXIT

emit_site_file_commands() {
  while IFS= read -r -d '' file_path; do
    local relative_path
    relative_path="${file_path#"$ROOT_DIR"/}"
    printf 'put "%s" "%s"\n' "$relative_path" "$relative_path" >> "$batch_file"
  done < <(
    find "$ROOT_DIR" -maxdepth 1 -type f \( -name '*.html' -o -name '*.txt' -o -name '*.xml' \) -print0 | sort -z
  )
}

emit_directory_commands() {
  local local_dir="$1"

  if [[ ! -d "$ROOT_DIR/$local_dir" ]]; then
    return
  fi

  printf -- '-mkdir "%s"\n' "$local_dir" >> "$batch_file"

  while IFS= read -r -d '' dir_path; do
    local relative_dir
    relative_dir="${dir_path#"$ROOT_DIR"/}"
    [[ "$relative_dir" == "$local_dir" ]] && continue
    printf -- '-mkdir "%s"\n' "$relative_dir" >> "$batch_file"
  done < <(
    find "$ROOT_DIR/$local_dir" -type d -print0 | sort -z
  )

  while IFS= read -r -d '' file_path; do
    local relative_path
    relative_path="${file_path#"$ROOT_DIR"/}"
    printf 'put "%s" "%s"\n' "$relative_path" "$relative_path" >> "$batch_file"
  done < <(
    find "$ROOT_DIR/$local_dir" -type f ! -name '.DS_Store' -print0 | sort -z
  )
}

emit_verify_urls() {
  cat <<'EOF'
/
/fido2_top.html
/integration_api.html
/passkey.html
EOF
}

verify_live_page() {
  local relative_path="$1"
  local local_file url local_hash remote_hash

  if [[ "$relative_path" == "/" ]]; then
    local_file="$ROOT_DIR/index.html"
    url="$LIVE_BASE_URL/"
  else
    local_file="$ROOT_DIR/${relative_path#/}"
    url="$LIVE_BASE_URL$relative_path"
  fi

  local_hash="$(shasum -a 256 "$local_file" | awk '{print $1}')"
  remote_hash="$(curl -LfsS "$url" | shasum -a 256 | awk '{print $1}')"

  if [[ "$local_hash" != "$remote_hash" ]]; then
    printf 'Verification failed for %s\n' "$url" >&2
    return 1
  fi

  printf 'Verified %s\n' "$url"
}

printf 'cd "%s"\n' "$REMOTE_DIR" > "$batch_file"
emit_site_file_commands
emit_directory_commands files

echo "Deploying to $SFTP_USER@$SFTP_HOST:$REMOTE_DIR"
sftp -b "$batch_file" "$SFTP_USER@$SFTP_HOST"

if command -v curl >/dev/null 2>&1 && command -v shasum >/dev/null 2>&1; then
  while IFS= read -r verify_path; do
    verify_live_page "$verify_path"
  done < <(emit_verify_urls)
else
  echo "Skipped live verification because curl or shasum is unavailable."
fi

echo "Deployment complete."