#!/usr/bin/env bash
# Upload changed plugin files to Cloudways staging via SFTP (lftp).
# Works when interactive SSH on port 22 is blocked; SFTP often still allowed.
#
# Optional: WI_UPLOAD_VERIFY=0 skips post-upload version check. Default: after uploading
# webinarignition.php, lftp re-downloads it and compares * Version + WEBINARIGNITION_VERSION
# to the local file (scripts/lib/wi-upload-verify.sh).
#
# Prereq: brew install lftp
# Setup: cp .env.cloudways-staging.local.example .env.cloudways-staging.local && edit.
# Local .env is the source of truth for staging SFTP.
#
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
ENV_FILE="${WI_CW_STAGING_ENV_FILE:-$ROOT/.env.cloudways-staging.local}"

# If all SFTP vars are already set by the shell, skip sourcing the local .env file.
if [[ -z "${WI_CW_STAGING_SFTP_HOST:-}" || -z "${WI_CW_STAGING_SFTP_USER:-}" || -z "${WI_CW_STAGING_SFTP_PASS:-}" || -z "${WI_CW_STAGING_REMOTE_PLUGIN_ROOT:-}" ]]; then
  if [[ ! -f "$ENV_FILE" ]]; then
    echo "Missing: $ENV_FILE"
    echo "Create it from .env.cloudways-staging.local.example and fill the local SFTP password."
    exit 1
  fi
  # shellcheck disable=SC1090
  set -a
  source "$ENV_FILE"
  set +a
fi

: "${WI_CW_STAGING_SFTP_HOST:?}"
: "${WI_CW_STAGING_SFTP_USER:?}"
: "${WI_CW_STAGING_SFTP_PASS:?}"
: "${WI_CW_STAGING_REMOTE_PLUGIN_ROOT:?}"

WI_CW_STAGING_SFTP_PORT="${WI_CW_STAGING_SFTP_PORT:-22}"
SFTP_URL="sftp://${WI_CW_STAGING_SFTP_HOST}:${WI_CW_STAGING_SFTP_PORT}"

FILES=(
  "webinarignition.php"
  "inc/wi-asset-version.php"
  "inc/class.WebinarignitionUpdates.php"
  "inc/class.WebinarignitionAjax.php"
  "inc/wi-frontend-functions.php"
  "inc/lp/webinar-modern.php"
  "inc/assets/class-frontend-scripts.php"
  "assets/webinarignition-cta-live-frontend.js"
)

puts=()
for f in "${FILES[@]}"; do
  if [[ -f "$ROOT/$f" ]]; then
    # No `put -c` (resume): it compares file size during transfer; editors/indexers can touch mtime/size
    # and lftp exits with "file size increased during transfer" even if you did not "save" consciously.
    puts+=( "put ${f}" )
  else
    echo "Skip (missing): $f"
  fi
done

if [[ ${#puts[@]} -eq 0 ]]; then
  echo "Nothing to upload."
  exit 0
fi

echo "lftp -> ${SFTP_URL}/${WI_CW_STAGING_REMOTE_PLUGIN_ROOT} (user ${WI_CW_STAGING_SFTP_USER})"

# One lftp session = one TCP+SSH handshake (faster than N separate scp calls).
# SSH: Compression=no saves CPU on fast links; keepalives reduce stalls on NAT.
{
  echo "set sftp:auto-confirm yes"
  echo "set cmd:fail-exit no"
  echo "set net:timeout 30"
  echo "set net:max-retries 2"
  echo "set net:reconnect-interval-base 2"
  echo 'set sftp:connect-program "ssh -a -x -o BatchMode=no -o IdentitiesOnly=yes -o IdentityFile=/dev/null -o NumberOfPasswordPrompts=1 -o PubkeyAuthentication=no -o PreferredAuthentications=password -o Compression=no -o ServerAliveInterval=20 -o ServerAliveCountMax=3 -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15"'
  echo "cd ${WI_CW_STAGING_REMOTE_PLUGIN_ROOT}"
  echo "lcd ${ROOT}"
  for line in "${puts[@]}"; do echo "$line"; done
  echo "bye"
} | lftp -u "${WI_CW_STAGING_SFTP_USER},${WI_CW_STAGING_SFTP_PASS}" "${SFTP_URL}"

# Re-fetch remote webinarignition.php when it was uploaded — proves server file matches local (same as wp2leads-live-sftp.sh).
WI_UPLOAD_VERIFY="${WI_UPLOAD_VERIFY:-1}"
uploaded_webinarignition_php=false
for f in "${FILES[@]}"; do
  if [[ "$f" == "webinarignition.php" ]]; then
    uploaded_webinarignition_php=true
    break
  fi
done
if [[ "${WI_UPLOAD_VERIFY}" != "0" && "${uploaded_webinarignition_php}" == "true" ]]; then
  # shellcheck source=scripts/lib/wi-upload-verify.sh
  source "${ROOT}/scripts/lib/wi-upload-verify.sh"
  REMOTE_VERIFY_PHP="$(mktemp)"
  trap 'rm -f "${REMOTE_VERIFY_PHP}"' EXIT
  {
    echo "set sftp:auto-confirm yes"
    echo "set cmd:fail-exit yes"
    echo "set net:timeout 30"
    echo "set net:max-retries 2"
    echo 'set sftp:connect-program "ssh -a -x -o BatchMode=no -o IdentitiesOnly=yes -o IdentityFile=/dev/null -o NumberOfPasswordPrompts=1 -o PubkeyAuthentication=no -o PreferredAuthentications=password -o Compression=no -o ServerAliveInterval=20 -o ServerAliveCountMax=3 -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15"'
    echo "cd ${WI_CW_STAGING_REMOTE_PLUGIN_ROOT}"
    echo "lcd ${ROOT}"
    echo "get -o ${REMOTE_VERIFY_PHP} webinarignition.php"
    echo "bye"
  } | lftp -u "${WI_CW_STAGING_SFTP_USER},${WI_CW_STAGING_SFTP_PASS}" "${SFTP_URL}" || {
    echo "wi-upload-verify: lftp get webinarignition.php failed" >&2
    exit 1
  }
  wi_upload_assert_remote_plugin_matches_local "${ROOT}/webinarignition.php" "${REMOTE_VERIFY_PHP}"
  trap - EXIT
  rm -f "${REMOTE_VERIFY_PHP}"
fi

echo "Done. When SSH works again: ssh ... 'cd public_html && wp cache flush'"
