#!/usr/bin/env bash
# Build the production site, upload the app over FTPS, then restart Passenger.
# The FTP password is prompted for and is never written to disk.
set -euo pipefail

cd "$(dirname "$0")/.."

FTP_HOST="${FTP_HOST:-premium285-4.web-hosting.com}"
FTP_USER="${FTP_USER:-stretimftp@stretim.com}"
FTP_REMOTE_PATH="${FTP_REMOTE_PATH:-/}"

web_dir="$(cd web && pwd -P)"
for pid in $(pgrep -f '[n]ext dev' || true); do
  process_dir="$(lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | sed -n 's/^n//p')"
  if [ "$process_dir" = "$web_dir" ]; then
    echo "next dev is running in web/ (pid $pid) and may overwrite the production build. Stop it first." >&2
    exit 1
  fi
done

if [ -z "${SKIP_BUILD:-}" ]; then
  echo "Building web/ for production..."
  npm run build
fi

if [ ! -f web/.next/BUILD_ID ]; then
  echo "web/.next is not a production build. Run without SKIP_BUILD." >&2
  exit 1
fi

files=()
while IFS= read -r -d '' file; do
  files+=("${file#./}")
done < <(
  find . -type f \
    ! -path './node_modules/*' \
    ! -path '*/node_modules/*' \
    ! -path './.git/*' \
    ! -path '*/.git/*' \
    ! -path './web/.next/cache/*' \
    ! -name '.env' \
    ! -name '.env.*' \
    ! -name '.env.local' \
    ! -name '.env.development.local' \
    ! -name '.env.production' \
    ! -name '.env.production.local' \
    ! -name '.DS_Store' \
    ! -name '*.log' \
    -print0
)

if [ "${#files[@]}" -eq 0 ]; then
  echo "No files found to upload." >&2
  exit 1
fi

echo
echo "Uploading ${#files[@]} files to ${FTP_USER} on ${FTP_HOST}${FTP_REMOTE_PATH}"
read -r -s -p "FTP password: " FTP_PASS
echo
export FTP_HOST FTP_USER FTP_PASS FTP_REMOTE_PATH

tmp="$(mktemp -d)"
trap 'unset FTP_PASS; rm -rf "$tmp"' EXIT
printf 'restart\n' > "$tmp/restart.txt"

curl_config() {
  node -e '
    const { FTP_HOST: host, FTP_USER: user, FTP_PASS: pass, FTP_REMOTE_PATH: remote } = process.env;
    const quote = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
    const url = (path) => `ftp://${host}/` + (remote + "/" + path).split("/").filter(Boolean).map(encodeURIComponent).join("/");
    const lines = [`user = ${quote(user + ":" + pass)}`, "ftp-ssl-reqd", "ftp-create-dirs", "globoff", "fail", "silent", "show-error"];
    for (const item of process.argv.slice(1)) {
      const separator = item.indexOf("=");
      const local = separator < 0 ? item : item.slice(0, separator);
      const remotePath = separator < 0 ? local : item.slice(separator + 1);
      lines.push(`upload-file = ${quote(local)}`, `url = ${quote(url(remotePath))}`);
    }
    console.log(lines.join("\n"));
  ' "$@"
}

if ! curl_config "${files[@]}" | curl --config - --write-out '%{response_code} %{url_effective}\n' > "$tmp/uploads.log" 2>&1; then
  cat "$tmp/uploads.log" >&2
  echo "Upload failed; the app was not restarted." >&2
  exit 1
fi

if ! awk '$1 != 226 { failed = 1 } END { exit failed }' "$tmp/uploads.log"; then
  cat "$tmp/uploads.log" >&2
  echo "One or more FTP transfers did not complete; the app was not restarted." >&2
  exit 1
fi

# Passenger watches this marker to restart the Node.js app. Upload it only
# after every application file has transferred successfully.
if ! curl_config "$tmp/restart.txt=tmp/restart.txt" | curl --config - --show-error; then
  echo "Files uploaded, but the restart marker could not be uploaded." >&2
  exit 1
fi

unset FTP_PASS
echo
echo "All ${#files[@]} files uploaded and the app restart requested."
