#!/usr/bin/env bash
# =============================================================================
#  Jean-Paul Industries: deploy jpindustries.zip on Bluehost / cPanel
#
#  jpindustries.com is the main (primary) domain, so its web root is ~/public_html.
#  The website itself lives in ~/public_html/ws_jpindustries, and a small block
#  in ~/public_html/.htaccess serves every jpindustries.com request from that folder.
#  Other websites in public_html (cPanel addon domains) are not touched.
#
#  Usage (upload jpindustries.zip and deploy.sh to your home folder, then):
#     bash deploy.sh                    deploy ./jpindustries.zip (asks before changing anything)
#     bash deploy.sh --yes              deploy without questions (it still asks for the Claude API key if none is saved)
#     bash deploy.sh --rollback         undo the most recent deploy
#
#  Options:
#     --zip FILE          the package to deploy        (default: jpindustries.zip next to this script)
#     --keep-content      keep the live page content instead of the package's content
#     --keep-wordpress    leave old WordPress files at the top of public_html
#     --root DIR          the main domain's web root   (default ~/public_html)
#     --site DIR          the site folder              (default <root>/ws_jpindustries)
#     --php PATH          PHP binary to use (auto-detected)
#     --yes, -y           don't ask questions, except for a missing Claude API key
#     --set-key           save or replace the Claude API key on this account, then stop
#     --no-cron           don't install the blog scheduler
#     --no-ping           don't tell search engines about new or changed pages
#     --rollback [DIR]    restore the backup made by a deploy (latest if DIR omitted)
#     -h, --help          show this help
#
#  Every deploy first saves the site folder and everything else it changes in
#  ~/jpi-backups/deploy-<date>/. The editor password, email settings, uploaded images,
#  inquiry log, editor backups, blog posts and subscribers on the server are always kept.
#
#  Blog: jpindustries.com is on its own hosting account, so it keeps its own copy of the Claude API
#  key, encrypted in ~/.jpi (outside the website). The first deploy asks for it (press Enter to skip);
#  every later deploy finds it and uses it automatically. (If this account ever gets the shared
#  ~/.sites key your other sites use, that is used when no ~/.jpi key is saved.)
#  The scheduler (every 5 minutes) is installed with crontab.
# =============================================================================
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ZIP=""; ROOT="$HOME/public_html"; SITE=""; KEEP_CONTENT=0; KEEP_WP=0; PHP=""; YES=0
DO_ROLLBACK=0; ROLLBACK=""; SET_KEY=0; NO_CRON=0; NO_PING=0
CRON_MARK="# jpi-blog-cron (managed by deploy.sh)"
DOMAIN_URL="https://www.jpindustries.com"
BK_ROOT="$HOME/jpi-backups"
MARK_BEGIN="# BEGIN jpindustries.com"; MARK_END="# END jpindustries.com"

c_bold=$'\e[1m'; c_green=$'\e[32m'; c_yellow=$'\e[33m'; c_red=$'\e[31m'; c_off=$'\e[0m'
[ -t 1 ] || { c_bold=; c_green=; c_yellow=; c_red=; c_off=; }
step() { echo; echo "${c_bold}==> $*${c_off}"; }
ok()   { echo "  ${c_green}✓${c_off} $*"; }
warn() { echo "  ${c_yellow}!${c_off} $*"; }
die()  { echo "  ${c_red}✗ $*${c_off}" >&2; exit 1; }
usage() { awk 'NR>2 && /^# =====/ {exit} NR>2' "$0" | sed 's/^# \{0,1\}//'; exit 0; }
# Saves the Claude API key (read without echo) encrypted in ~/.jpi via the site's api/secrets.php.
# Can we ask the person running this a question? (true even with --yes, as long as a terminal is attached)
has_tty() { { : </dev/tty; } 2>/dev/null; }

# Asks for the Claude API key, saves it encrypted (api/secrets.php → ~/.jpi, outside the web root) and tests it.
# Up to 3 tries; Enter skips. Returns 0 when a working key was saved.
ask_claude_key() {
  local key="" tries=0 msg saved=0
  [ "${2:-}" = replace ] && saved=1   # a key is already saved but didn't work
  echo "  The blog drafts a post every two weeks with Claude. Paste your Claude API key"
  echo "  (it starts with sk-ant-; create one at https://console.anthropic.com/settings/keys)."
  echo "  It is stored encrypted in ~/.jpi on this hosting account, never in the website folder."
  while [ "$tries" -lt 3 ]; do
    tries=$((tries + 1))
    key=""
    read -r -s -p "  Claude API key (Enter to skip): " key </dev/tty || true; echo
    if [ -z "$key" ]; then
      if [ "$saved" = 1 ]; then warn "Kept the saved key, but Claude didn't accept it, so posts can't be drafted. Replace it with: bash deploy.sh --set-key"
      else warn "Skipped. The blog can't draft posts until a key is saved: bash deploy.sh --set-key"; fi
      return 1
    fi
    if ! printf '%s' "$key" | "$PHP" "$1/api/secrets.php" set claude_api_key >/dev/null 2>&1; then
      key=""; warn "That doesn't look like a Claude API key (they start with sk-ant-). Try again."
      continue
    fi
    key=""; saved=1
    ok "Claude API key saved (encrypted)"
    if msg="$("$PHP" "$1/api/secrets.php" test 2>/dev/null)"; then ok "$msg"; return 0; fi
    warn "${msg:-The test request to Claude failed.}"
    [ "$tries" -lt 3 ] && echo "  Paste a different key, or press Enter to keep the one just saved."
  done
  return 1
}
confirm() {
  [ "$YES" = 1 ] && return 0
  [ -t 0 ] || die "Run with --yes to deploy without questions."
  local a; read -r -p "  $1 [y/N]: " a </dev/tty || true
  [[ "$a" =~ ^[Yy] ]]
}

while [ $# -gt 0 ]; do
  case "$1" in
    --zip)            ZIP="${2:-}"; shift 2 ;;
    --keep-content)   KEEP_CONTENT=1; shift ;;
    --keep-wordpress) KEEP_WP=1; shift ;;
    --root)           ROOT="${2%/}"; shift 2 ;;
    --site)           SITE="${2%/}"; shift 2 ;;
    --php)            PHP="${2:-}"; shift 2 ;;
    --yes|-y)         YES=1; shift ;;
    --set-key)        SET_KEY=1; shift ;;
    --no-cron)        NO_CRON=1; shift ;;
    --no-ping)        NO_PING=1; shift ;;
    --rollback)       DO_ROLLBACK=1; if [ -n "${2:-}" ] && [ "${2#-}" = "$2" ]; then ROLLBACK="${2%/}"; shift; fi; shift ;;
    -h|--help)        usage ;;
    *.zip)            ZIP="$1"; shift ;;
    *)                die "Unknown option: $1 (see --help)" ;;
  esac
done
[ -d "$ROOT" ] || die "$ROOT does not exist."
ROOT="$(cd "$ROOT" && pwd)"
[ -n "$SITE" ] || SITE="$ROOT/ws_jpindustries"
SITE_NAME="$(basename "$SITE")"

# What the package puts in the site folder. Only these are ever replaced there.
ITEMS=(.htaccess index.php api app images favicon.ico favicon.svg apple-touch-icon.png site.webmanifest google75fb6750f2d1b990.html)
# Live data that belongs to the running site and is always kept.
KEEP_FILES=(api/config.php api/data/admin.json api/data/secret.key api/data/inquiries.log api/data/ratelimit.json api/data/login-attempts.json
            api/data/blog.sqlite api/data/cron-state.json api/data/cron.log api/data/claude-model.json api/data/ratelimit-subscribe.json
            api/data/visits.sqlite api/data/geo.sqlite api/data/google-certs.json
            api/data/indexnow-key.txt api/data/indexnow-state.json api/data/indexnow.log)
# Old WordPress files that may sit at the top of public_html.
WP_ITEMS=(wp-admin wp-content wp-includes wp-activate.php wp-blog-header.php wp-comments-post.php wp-config.php
          wp-config-sample.php wp-cron.php wp-links-opml.php wp-load.php wp-login.php wp-mail.php wp-settings.php
          wp-signup.php wp-trackback.php xmlrpc.php license.txt readme.html wordfence-waf.php)

echo "${c_bold}Jean-Paul Industries website deploy${c_off}"

# =============================================================================
#  Rollback
# =============================================================================
if [ "$DO_ROLLBACK" = 1 ]; then
  if [ -z "$ROLLBACK" ]; then
    ROLLBACK="$(ls -1d "$BK_ROOT"/deploy-* 2>/dev/null | sort | tail -1 || true)"
    [ -n "$ROLLBACK" ] || die "No deploy backups found in $BK_ROOT."
  fi
  [ -f "$ROLLBACK/manifest.txt" ] || die "$ROLLBACK is not a deploy backup (no manifest.txt)."
  step "Rolling back to the state saved in $ROLLBACK"
  sed 's/^/      /' "$ROLLBACK/manifest.txt"
  warn "Any edits made in /admin after that deploy will be lost."
  confirm "Restore it?" || die "Stopped. Nothing was changed."
  if [ -f "$ROLLBACK/site.tar.gz" ]; then
    rm -rf "$SITE"; mkdir -p "$SITE"; tar -xzpf "$ROLLBACK/site.tar.gz" -C "$SITE"; ok "Restored $SITE"
  elif grep -q "^Site folder was new" "$ROLLBACK/manifest.txt"; then
    rm -rf "$SITE"; ok "Removed $SITE (it didn't exist before)"
  fi
  if [ -f "$ROLLBACK/root.htaccess" ]; then cp -p "$ROLLBACK/root.htaccess" "$ROOT/.htaccess"; ok "Restored $ROOT/.htaccess"
  elif grep -q "^Top-level .htaccess was new" "$ROLLBACK/manifest.txt"; then rm -f "$ROOT/.htaccess"; ok "Removed $ROOT/.htaccess"; fi
  if [ -d "$ROLLBACK/moved-from-root" ]; then
    for p in "$ROLLBACK/moved-from-root"/* "$ROLLBACK/moved-from-root"/.[!.]*; do
      [ -e "$p" ] || continue; b="$(basename "$p")"
      if [ -e "$ROOT/$b" ]; then warn "Skipped $b (already exists)"; else mv "$p" "$ROOT/$b"; fi
    done
    ok "Put back the files that were moved out of $ROOT"
  fi
  echo "Rolled back on $(date)" >> "$ROLLBACK/manifest.txt"
  ok "Rolled back. The backup folder is kept: $ROLLBACK"
  exit 0
fi

# =============================================================================
#  Checks
# =============================================================================
step "Checking"

php_ok() {
  [ -x "$(command -v "$1" 2>/dev/null)" ] || return 1
  "$1" -r 'foreach (["mbstring","dom","json","session"] as $e) if (!extension_loaded($e)) exit(1); exit(version_compare(PHP_VERSION, "8.1.0", ">=") ? 0 : 1);' >/dev/null 2>&1
}
if [ -n "$PHP" ]; then php_ok "$PHP" || die "The PHP given with --php can't be used (needs 8.1+ with mbstring and dom): $PHP"
else
  for cand in php php84 php83 php82 php81 \
              /opt/cpanel/ea-php84/root/usr/bin/php /opt/cpanel/ea-php83/root/usr/bin/php \
              /opt/cpanel/ea-php82/root/usr/bin/php /opt/cpanel/ea-php81/root/usr/bin/php \
              /usr/local/bin/ea-php84 /usr/local/bin/ea-php83 /usr/local/bin/ea-php82 /usr/local/bin/ea-php81; do
    if php_ok "$cand"; then PHP="$cand"; break; fi
  done
  [ -n "$PHP" ] || die "PHP 8.1+ was not found. In cPanel → MultiPHP Manager set jpindustries.com to PHP 8.2 or newer, or run with --php /opt/cpanel/ea-php82/root/usr/bin/php"
fi
ok "PHP $("$PHP" -r 'echo PHP_VERSION;')  ($PHP)"

if [ "$SET_KEY" = 1 ]; then
  [ -f "$SITE/api/secrets.php" ] || die "Deploy the site first ($SITE/api/secrets.php not found)."
  has_tty || die "--set-key needs to be run in a terminal."
  "$PHP" "$SITE/api/secrets.php" status | sed 's/^/  /' || true
  ask_claude_key "$SITE" || exit 1
  exit 0
fi

[ -n "$ZIP" ] || ZIP="$HERE/jpindustries.zip"
[ -f "$ZIP" ] || die "Can't find $ZIP. Put jpindustries.zip next to deploy.sh (or use --zip FILE)."
case "$(cd "$(dirname "$ZIP")" && pwd)/" in "$ROOT/"*) warn "The zip is inside public_html, where anyone could download it. Move it to your home folder afterwards." ;; esac

TMP="$(mktemp -d "${TMPDIR:-/tmp}/jpi-deploy.XXXXXX")"; trap 'rm -rf "$TMP"' EXIT
PKG="$TMP/pkg"; mkdir -p "$PKG"
if command -v unzip >/dev/null 2>&1; then unzip -q "$ZIP" -d "$PKG"
else "$PHP" -r '$z = new ZipArchive; if ($z->open($argv[1]) !== true || !$z->extractTo($argv[2])) exit(1);' "$ZIP" "$PKG" || die "Could not unzip $ZIP"; fi
# Accept a zip with the files at the top, or inside one folder.
if [ ! -f "$PKG/index.php" ]; then
  inner="$(find "$PKG" -mindepth 2 -maxdepth 3 -name index.php -path '*/index.php' | grep -v '/api/' | head -1 || true)"
  [ -n "$inner" ] && PKG="$(dirname "$inner")"
fi
[ -f "$PKG/index.php" ] && [ -f "$PKG/.htaccess" ] && [ -f "$PKG/app/index.html" ] && [ -f "$PKG/api/lib.php" ] \
  || die "$ZIP doesn't look like the jpindustries.com package (index.php, .htaccess, app/ and api/ at the top)."
ok "Package: $(basename "$ZIP")"

HAVE_SITE=0; [ -f "$SITE/api/data/content.json" ] && HAVE_SITE=1
USE_PKG_CONTENT=1
if [ "$HAVE_SITE" = 1 ] && [ -f "$PKG/api/data/content.json" ]; then
  if [ "$KEEP_CONTENT" = 1 ]; then USE_PKG_CONTENT=0
  elif [ "$(stat -c %Y "$SITE/api/data/content.json")" -gt "$(stat -c %Y "$PKG/api/data/content.json")" ]; then
    warn "The live page content was changed (in /admin) after this package was built."
    if [ "$YES" = 1 ]; then USE_PKG_CONTENT=0; warn "Keeping the live content. Run without --yes to choose."
    elif confirm "Replace the live page content with the package's content anyway?"; then USE_PKG_CONTENT=1
    else USE_PKG_CONTENT=0; fi
  fi
fi
[ -f "$PKG/api/data/content.json" ] || USE_PKG_CONTENT=0

WP_FOUND=()
for w in "${WP_ITEMS[@]}"; do [ -e "$ROOT/$w" ] && WP_FOUND+=("$w"); done
HAS_WP=0
if [ -e "$ROOT/wp-config.php" ] || [ -d "$ROOT/wp-includes" ]; then HAS_WP=1; fi
if [ "$HAS_WP" = 1 ]; then
  [ -f "$ROOT/index.php" ] && grep -q "wp-blog-header" "$ROOT/index.php" && WP_FOUND+=("index.php")
  [ -f "$ROOT/.user.ini" ] && grep -q "wordfence" "$ROOT/.user.ini" && WP_FOUND+=(".user.ini")
fi
# Leftovers from a copy of this site at the top of public_html (it is served from the site folder now).
OURS_AT_ROOT=()
if [ -f "$ROOT/api/lib.php" ] && grep -q "function home_payload" "$ROOT/api/lib.php" 2>/dev/null; then
  for it in "${ITEMS[@]}"; do [ "$it" = .htaccess ] && continue; [ -e "$ROOT/$it" ] && OURS_AT_ROOT+=("$it"); done
fi

# Where the live data (password, settings, inquiries, uploads) comes from.
DATA_SRC=""
ROOT_COPY=0; if [ ${#OURS_AT_ROOT[@]} -gt 0 ] && [ -f "$ROOT/api/data/content.json" ]; then ROOT_COPY=1; fi
if [ "$HAVE_SITE" = 1 ] && [ "$ROOT_COPY" = 1 ]; then
  # Both exist: the live one is whichever was changed most recently (password or content).
  newest() { stat -c %Y "$1/api/data/admin.json" "$1/api/data/content.json" 2>/dev/null | sort -n | tail -1; }
  if [ "$(newest "$ROOT")" -gt "$(newest "$SITE")" ]; then DATA_SRC="$ROOT"; else DATA_SRC="$SITE"; fi
elif [ "$HAVE_SITE" = 1 ]; then DATA_SRC="$SITE"
elif [ "$ROOT_COPY" = 1 ]; then DATA_SRC="$ROOT"
  if [ "$KEEP_CONTENT" = 1 ]; then USE_PKG_CONTENT=0; fi
fi

# =============================================================================
#  Plan
# =============================================================================
step "Plan"
if [ "$HAVE_SITE" = 1 ]; then ok "Update the site in $SITE"; else ok "Install the site into $SITE (new folder)"; fi
if [ "$USE_PKG_CONTENT" = 1 ]; then ok "Page content: from the package"; else ok "Page content: keep the live content"; fi
if [ -n "$DATA_SRC" ]; then ok "Kept from $DATA_SRC: editor password, email settings, uploaded images, inquiry log, editor backups"
else warn "No live copy of the site found; you'll choose an editor password."; fi
ok "Add the jpindustries.com block to $ROOT/.htaccess (https://www. redirect + serve from $SITE_NAME)"
if [ "$HAS_WP" = 1 ] && [ "$KEEP_WP" = 0 ]; then
  warn "Old WordPress files at the top of public_html will be MOVED OUT to the backup folder (not deleted):"
  echo "      ${WP_FOUND[*]}"
fi
if [ ${#OURS_AT_ROOT[@]} -gt 0 ]; then warn "An older copy of this site at the top of public_html will be moved to the backup folder: ${OURS_AT_ROOT[*]}"; fi
echo
confirm "Go ahead?" || die "Stopped. Nothing was changed."

# =============================================================================
#  Backup
# =============================================================================
STAMP="$(date +%Y%m%d-%H%M%S)"
BK="$BK_ROOT/deploy-$STAMP"
mkdir -p "$BK"; chmod 700 "$BK_ROOT" "$BK"
step "Backing up to $BK"
echo "Deploy of $(basename "$ZIP") on $(date). Site folder: $SITE" > "$BK/manifest.txt"
# (The country database is left out of the backup: it is public data that reinstalls itself.)
if [ -d "$SITE" ]; then tar -czpf "$BK/site.tar.gz" --exclude=./api/data/geo.sqlite --exclude=./api/data/geo.sqlite.new -C "$SITE" . ; ok "Saved $SITE ($(du -h "$BK/site.tar.gz" | cut -f1))"
else echo "Site folder was new" >> "$BK/manifest.txt"; fi
if [ -f "$ROOT/.htaccess" ]; then cp -p "$ROOT/.htaccess" "$BK/root.htaccess"; ok "Saved $ROOT/.htaccess"
else echo "Top-level .htaccess was new" >> "$BK/manifest.txt"; fi
MOVE=()
if [ "$HAS_WP" = 1 ] && [ "$KEEP_WP" = 0 ]; then MOVE+=("${WP_FOUND[@]}"); fi
if [ ${#OURS_AT_ROOT[@]} -gt 0 ]; then MOVE+=("${OURS_AT_ROOT[@]}"); fi
if [ ${#MOVE[@]} -gt 0 ]; then
  mkdir -p "$BK/moved-from-root"
  for m in "${MOVE[@]}"; do [ -e "$ROOT/$m" ] && mv "$ROOT/$m" "$BK/moved-from-root/"; done
  echo "Moved out of $ROOT: ${MOVE[*]}" >> "$BK/manifest.txt"
  ok "Moved to $BK/moved-from-root: ${MOVE[*]}"
fi

# =============================================================================
#  Site folder
# =============================================================================
step "Updating $SITE"
mkdir -p "$SITE"
KEEP="$TMP/keep"; mkdir -p "$KEEP"
# (An older copy at the top of public_html was already moved to the backup folder; read its data from there.)
SRC_DIR="$DATA_SRC"; [ "$DATA_SRC" = "$ROOT" ] && SRC_DIR="$BK/moved-from-root"
if [ -n "$SRC_DIR" ]; then
  for f in "${KEEP_FILES[@]}"; do [ -e "$SRC_DIR/$f" ] && { mkdir -p "$KEEP/$(dirname "$f")"; cp -p "$SRC_DIR/$f" "$KEEP/$f"; }; done
  [ -d "$SRC_DIR/api/data/backups" ] && { mkdir -p "$KEEP/api/data"; cp -Rp "$SRC_DIR/api/data/backups" "$KEEP/api/data/"; }
  [ -d "$SRC_DIR/images/uploads" ] && { mkdir -p "$KEEP/images"; cp -Rp "$SRC_DIR/images/uploads" "$KEEP/images/"; }
  if [ "$USE_PKG_CONTENT" = 0 ] && [ -f "$SRC_DIR/api/data/content.json" ]; then mkdir -p "$KEEP/api/data"; cp -p "$SRC_DIR/api/data/content.json" "$KEEP/api/data/"; fi
fi

for it in "${ITEMS[@]}"; do
  [ -e "$PKG/$it" ] || continue
  rm -rf "$SITE/$it"
  cp -Rp "$PKG/$it" "$SITE/$it"
done
# Put the live data back (uploads are merged: the package's images plus everything uploaded in /admin).
cp -Rp "$KEEP/." "$SITE/"
ok "Site files in place (live data kept)"

# =============================================================================
#  Top-level .htaccess
# =============================================================================
step "Top-level .htaccess"
HT="$ROOT/.htaccess"
BLOCK="$TMP/block"
cat > "$BLOCK" <<'HTB'
# BEGIN jpindustries.com (managed by deploy.sh; do not edit between these lines)
# jpindustries.com is the main domain of this hosting account. Its website lives in the
# __SITE__ folder; these rules serve every jpindustries.com request from there,
# so visitors still see clean addresses like https://www.jpindustries.com/company.
# Other domains (cPanel addon domains) are not affected.
<IfModule mod_rewrite.c>
RewriteEngine On

# 1) One permanent redirect to https://www.jpindustries.com (SSL renewal checks under /.well-known are left alone)
RewriteCond %{HTTP_HOST} ^(www\.)?jpindustries\.com(:\d+)?$ [NC]
RewriteCond %{REQUEST_URI} !^/\.well-known/
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^jpindustries\.com(:\d+)?$ [NC]
RewriteRule ^(.*)$ https://www.jpindustries.com/$1 [R=301,L]

# 2) Serve everything for jpindustries.com from the __SITE__ folder
RewriteCond %{HTTP_HOST} ^(www\.)?jpindustries\.com(:\d+)?$ [NC]
RewriteCond %{REQUEST_URI} !^/__SITE_RE__/
RewriteCond %{REQUEST_URI} !^/\.well-known/
RewriteCond %{REQUEST_URI} !^/cgi-bin/
RewriteRule ^(.*)$ /__SITE__/$1 [L]
</IfModule>
# END jpindustries.com
HTB
SITE_RE="$(printf '%s' "$SITE_NAME" | sed 's/[.]/\\\\./g')"
sed -i -e "s|__SITE_RE__|$SITE_RE|g" -e "s|__SITE__|$SITE_NAME|g" "$BLOCK"
# Keep everything else in the current file (cPanel's PHP version settings, other sites' rules),
# minus an older copy of our block and the WordPress block when WordPress was moved out.
REST="$TMP/rest"; : > "$REST"
if [ -f "$HT" ] && grep -q "JSON API: /api/site" "$HT"; then
  # It's an older copy of this site's own .htaccess: keep only cPanel's generated blocks from it.
  awk '
    /^# php -- BEGIN cPanel-generated handler/ || /^# BEGIN cPanel-generated php ini directives/ { keep=1 }
    keep { print }
    /^# php -- END cPanel-generated handler/ || /^# END cPanel-generated php ini directives/ { keep=0; print "" }
  ' "$HT" > "$REST"
elif [ -f "$HT" ]; then
  DROP_WP=0; if [ "$HAS_WP" = 1 ] && [ "$KEEP_WP" = 0 ]; then DROP_WP=1; fi
  awk -v dropwp="$DROP_WP" '
    /^# BEGIN jpindustries\.com/ { skip=1 }
    dropwp==1 && /^# BEGIN WordPress/ { skip=1 }
    !skip { print }
    /^# END jpindustries\.com/ { skip=0; next }
    dropwp==1 && /^# END WordPress/ { skip=0; next }
  ' "$HT" > "$REST"
fi
{ cat "$BLOCK"; echo; cat "$REST"; } | cat -s > "$HT.new" && mv "$HT.new" "$HT"
chmod 644 "$HT"
ok "jpindustries.com is served from $SITE_NAME, with the https://www. redirect"
if grep -q "cPanel-generated" "$HT"; then ok "Kept cPanel's PHP settings in the same file"; fi

# =============================================================================
#  Password, permissions
# =============================================================================
step "Settings"
CFG="$SITE/api/config.php"
"$PHP" -r '
  [$f, $u] = array_slice($argv, 1);
  $s = file_get_contents($f);
  if (preg_match("/\x27site_url\x27\s*=>/", $s)) $s = preg_replace("/(\x27site_url\x27\s*=>\s*)\x27[^\x27]*\x27/", "\${1}" . var_export($u, true), $s, 1);
  else $s = preg_replace("/return \[\n/", "return [\n    \x27site_url\x27       => " . var_export($u, true) . ",\n", $s, 1);
  file_put_contents($f, $s);
' "$CFG" "$DOMAIN_URL"
ok "Site address: $DOMAIN_URL"
# Settings added in newer versions (blog, visitor log, …) are copied into the live config.php
# from the package's copy. Existing settings are never changed.
ADDED="$("$PHP" -r '
  [$live, $pkg] = array_slice($argv, 1);
  $L = require $live; $P = require $pkg;
  if (!is_array($L) || !is_array($P)) exit(0);
  $missing = array_diff_key($P, $L);
  if (!$missing) exit(0);
  $src = file($pkg); $add = "";
  foreach (array_keys($missing) as $k) {
    $line = null;
    foreach ($src as $l) if (preg_match("/^\s*\x27" . preg_quote($k, "/") . "\x27\s*=>.*,\s*(\/\/.*)?$/", rtrim($l))) { $line = rtrim($l); break; }
    if ($line === null || (str_contains($line, "__DIR__") === false && strpos($line, "[") !== false && strpos($line, "]") === false)) $line = "    " . var_export($k, true) . " => " . var_export($P[$k], true) . ",";
    $add .= $line . "\n";
  }
  $s = file_get_contents($live);
  $pos = strrpos($s, "];");
  if ($pos === false) exit(0);
  $s = substr($s, 0, $pos) . "\n    // ---- Added by deploy.sh on " . date("Y-m-d") . " (settings from a newer version) ----\n" . $add . substr($s, $pos);
  file_put_contents($live, $s);
  echo implode(", ", array_keys($missing));
' "$CFG" "$PKG/api/config.php" 2>/dev/null || true)"
if [ -n "$ADDED" ]; then ok "New settings added to config.php: $ADDED"; else ok "config.php has every setting"; fi
"$PHP" -l "$CFG" >/dev/null 2>&1 || die "config.php has a syntax error after the update. Undo with:  bash deploy.sh --rollback"
ok "Inquiries go to: $("$PHP" -r '$c = require $argv[1]; echo $c["contact_to"];' "$CFG")"
if [ -f "$SITE/api/data/admin.json" ]; then
  ok "Editor password unchanged"
else
  if [ "$YES" = 1 ] || [ ! -t 0 ]; then
    PW="JPI-$("$PHP" -r 'echo bin2hex(random_bytes(6));')"
    "$PHP" "$SITE/api/set-password.php" "$PW" >/dev/null
    ok "Editor password generated: ${c_bold}$PW${c_off}  (write it down; change it in /admin → Password)"
  else
    while :; do
      read -r -s -p "  Choose a password for the site editor (/admin), at least 10 characters: " PW </dev/tty; echo
      [ "${#PW}" -ge 10 ] || { warn "Too short."; continue; }
      read -r -s -p "  Type it again: " P2 </dev/tty; echo
      [ "$PW" = "$P2" ] && break || warn "They didn't match."
    done
    "$PHP" "$SITE/api/set-password.php" "$PW" >/dev/null; ok "Editor password set"
  fi
fi
mkdir -p "$SITE/api/data/backups" "$SITE/images/uploads"
find "$SITE" -type d -exec chmod 755 {} + ; find "$SITE" -type f -exec chmod 644 {} +
chmod 600 "$SITE/api/data/admin.json"; [ -f "$SITE/api/data/secret.key" ] && chmod 600 "$SITE/api/data/secret.key"
ok "Permissions set on $SITE_NAME"

# =============================================================================
#  Blog: database, Claude API key, hourly scheduler
# =============================================================================
step "Blog"
BLOG_OK=1
for ext in pdo_sqlite curl openssl; do
  "$PHP" -r "exit(extension_loaded('$ext') ? 0 : 1);" || { warn "PHP extension $ext is missing; the blog needs it (cPanel → Select PHP Version → Extensions)."; BLOG_OK=0; }
done
if [ "$BLOG_OK" = 1 ]; then
  ( cd "$SITE" && "$PHP" -r 'require "api/lib.php"; require "api/blog.php"; blog_db();' ) >/dev/null 2>&1 \
    && ok "Blog database opens" || warn "The blog database could not be opened."
  [ -f "$SITE/api/data/blog.sqlite" ] && chmod 600 "$SITE/api/data/blog.sqlite"
  # The Claude API key: use the one saved (encrypted) on this account if it works; otherwise ask for it,
  # even with --yes, because the blog can't draft posts without it.
  if KEYMSG="$("$PHP" "$SITE/api/secrets.php" status 2>&1)"; then
    ok "$(printf '%s\n' "$KEYMSG" | grep '^Claude API key' | head -1)"
    if TESTMSG="$("$PHP" "$SITE/api/secrets.php" test 2>/dev/null)"; then
      ok "$TESTMSG"
    else
      warn "${TESTMSG:-The test request to Claude failed.}"
      if has_tty; then
        echo "  The saved key didn't work. Paste a new one to replace it (Enter keeps the saved key)."
        ask_claude_key "$SITE" replace || true
      else
        warn "Replace it with: bash deploy.sh --set-key"
      fi
    fi
  else
    warn "No Claude API key is saved on this hosting account yet."
    if has_tty; then
      ask_claude_key "$SITE" || true
    else
      warn "No terminal to ask in, so posts won't be drafted. Save the key with: bash deploy.sh --set-key"
    fi
  fi
fi
if [ "$NO_CRON" = 1 ]; then
  warn "Scheduler not installed (--no-cron). Posts won't publish or email automatically."
elif command -v crontab >/dev/null 2>&1; then
  CRON_LINE="*/5 * * * * cd \"$SITE\" && \"$PHP\" api/cron.php >/dev/null 2>&1 $CRON_MARK"
  { crontab -l 2>/dev/null | grep -vF "$CRON_MARK" || true; echo "$CRON_LINE"; } | crontab - \
    && ok "Blog scheduler installed, every 5 minutes (cPanel → Cron Jobs shows it)" \
    || warn "Couldn't install the scheduler. In cPanel → Cron Jobs add, every 5 minutes:  cd $SITE && $PHP api/cron.php"
else
  warn "crontab isn't available. In cPanel → Cron Jobs add, every 5 minutes:  cd $SITE && $PHP api/cron.php"
fi

# =============================================================================
#  Checks
# =============================================================================
step "Visitor log"
[ -f "$SITE/api/data/visits.sqlite" ] && chmod 600 "$SITE/api/data/visits.sqlite"
if ! "$PHP" -r "exit(extension_loaded('pdo_sqlite') ? 0 : 1);"; then
  warn "PHP pdo_sqlite is missing, so visits can't be logged (cPanel → Select PHP Version → Extensions)."
elif [ -f "$SITE/api/data/geo.sqlite" ]; then
  ok "$( cd "$SITE" && "$PHP" api/geo.php status )"
else
  echo "  Installing the country database (DB-IP IP to Country Lite, free, about 35 MB)…"
  if ( cd "$SITE" && "$PHP" api/geo.php update 2>&1 ) | sed 's/^/  /'; [ "${PIPESTATUS[0]}" = 0 ]; then ok "Country database installed"
  else warn "The country database couldn't be downloaded now; the scheduler retries once a day (or run: cd $SITE && $PHP api/geo.php update)"; fi
fi
ok "Every page view is logged; see $DOMAIN_URL/admin → Visitors"

step "Checking the site"
( cd "$SITE" && "$PHP" -r 'require "api/lib.php"; $c = content(); echo "  ", count($c["pages"]), " pages loaded\n";
    foreach (["api/data", "images/uploads"] as $d) if (!is_writable($d)) { echo "  (!) $d is not writable\n"; }' ) \
  || die "The site's PHP code failed to run. Undo with:  bash deploy.sh --rollback"
ok "Site code and content load"
if command -v curl >/dev/null 2>&1; then
  sleep 1
  CK="${JPI_CHECK_URL:-$DOMAIN_URL}"; CKH="${JPI_CHECK_HTTP:-http://jpindustries.com}"
  chk() { local c; c="$(curl -sk -o /dev/null -w '%{http_code}' --max-time 20 "$1" 2>/dev/null || true)"; echo "${c:-000}"; }
  a="$(chk "$CK/")"
  if [ "$a" = 000 ]; then
    warn "Couldn't reach $CK from the server. Check the site in your browser."
  else
    r() { if [ "$2" = "$3" ]; then ok "$1: $2"; else warn "$1 returned $2 (expected $3)"; fi; }
    r "Home page" "$a" 200
    r "Inner page /company" "$(chk "$CK/company")" 200
    r "API /api/site" "$(chk "$CK/api/site")" 200
    r "Private data /api/data/content.json" "$(chk "$CK/api/data/content.json")" 403
    r "Private data /api/data/blog.sqlite" "$(chk "$CK/api/data/blog.sqlite")" 403
    r "Private data /api/data/visits.sqlite" "$(chk "$CK/api/data/visits.sqlite")" 403
    r "Private data /api/data/inquiries.log" "$(chk "$CK/api/data/inquiries.log")" 403
    r "Country tool not reachable from the web (/api/geo.php)" "$(chk "$CK/api/geo.php")" 404
    r "Blog /blog" "$(chk "$CK/blog")" 200
    r "Blog API /api/blog" "$(chk "$CK/api/blog")" 200
    r "Scheduler not reachable from the web (/api/cron.php)" "$(chk "$CK/api/cron.php")" 404
    r "Sitemap /sitemap.xml" "$(chk "$CK/sitemap.xml")" 200
    r "http://jpindustries.com redirect" "$(chk "$CKH/company")" 301
    r "Folder name in the address (/$SITE_NAME/company) redirects" "$(chk "$CK/$SITE_NAME/company")" 301
    t="$(curl -sk --max-time 20 "$CK/" 2>/dev/null | grep -o '<title>[^<]*' | head -1 || true)"
    if [ -n "$t" ]; then ok "Home page title: ${t#<title>}"; fi
    if [ "$a" != 200 ]; then warn "If the site is broken, undo with:  bash deploy.sh --rollback"; fi
  fi
fi

# =============================================================================
#  Search engines (api/indexnow.php)
# =============================================================================
step "Search engines"
if [ "$NO_PING" = 1 ]; then
  warn "Not submitted (--no-ping)."
elif ! command -v curl >/dev/null 2>&1 || [ "${a:-000}" != 200 ]; then
  warn "Not submitted: the site didn't answer the checks above. Once it works, run:  cd $SITE && $PHP api/indexnow.php"
else
  IKEY="$( cd "$SITE" && "$PHP" -r 'require "api/indexnow.php"; echo indexnow_key();' )"
  kc="$(chk "$CK/$IKEY.txt")"
  if [ "$kc" != 200 ]; then
    warn "The IndexNow key file $CK/$IKEY.txt returned $kc, so nothing was submitted."
  elif out="$( cd "$SITE" && "$PHP" api/indexnow.php 2>&1 )"; then
    ok "$out"
  else
    warn "$out"
  fi
  ok "Sitemap for all search engines: $DOMAIN_URL/sitemap.xml (listed in robots.txt)"
  echo "  Google doesn't accept IndexNow; it reads the sitemap. Add the site once in Google Search Console"
  echo "  (search.google.com/search-console) and submit $DOMAIN_URL/sitemap.xml there."
fi

# =============================================================================
#  Review of the scheduled jobs and the blog (api/cron.php --review)
# =============================================================================
step "Scheduled jobs and blog review"
if [ "$NO_CRON" != 1 ] && [ "${BLOG_OK:-1}" = 1 ]; then
  # Run the scheduler once now, as cron would: it publishes due posts and, if a post is due, asks Claude to draft it
  # (that can take a few minutes). Its output shows what it did.
  echo "  Running the scheduler once now…"
  if command -v timeout >/dev/null 2>&1; then
    ( cd "$SITE" && timeout 420 "$PHP" api/cron.php 2>&1 ) | sed 's/^/  │ /' || true
  else
    ( cd "$SITE" && "$PHP" api/cron.php 2>&1 ) | sed 's/^/  │ /' || true
  fi
fi
REVIEW="$( cd "$SITE" && "$PHP" api/cron.php --review 2>&1 )" || true
while IFS= read -r line; do
  case "$line" in
    OK:*)     ok "${line#OK: }" ;;
    WARN:*)   warn "${line#WARN: }" ;;
    INFO:*)   echo "  ${line#INFO: }" ;;
    RESULT:*) REVIEW_RESULT="${line#RESULT: }" ;;
    "")       ;;
    *)        echo "  $line" ;;
  esac
done <<< "$REVIEW"
[ -n "${REVIEW_RESULT:-}" ] && echo "  ${c_bold}${REVIEW_RESULT}${c_off}"
echo "  Run this review any time:  cd $SITE && $PHP api/cron.php --review"

echo
echo "${c_green}${c_bold}Deployed.${c_off}"
echo "  Website:  $DOMAIN_URL"
echo "  Admin:    $DOMAIN_URL/admin   (Visitors, Inquiries, Blog; Account tab: Google sign-in)"
echo "  Blog:     $DOMAIN_URL/blog"
echo "  Backup:   $BK"
echo "  Undo:     bash deploy.sh --rollback"
