#!/bin/bash
#
# Delete the mostafaei install and put a blank one in its place.
#
# Why rebuild rather than repair: mostafaei was installed by rsyncing Final
# Target's working tree onto a second domain, before ft-tenant-install.sh
# existed. It therefore carries Final Target's content rows, Final Target's
# settings row, and templates with the name written into them. Repairing that
# means finding every one of them, and the way you find out you missed one is a
# client reading it. A blank install cannot carry what it was never given.
#
# What is kept: the images, and a full dump of everything else in case a
# decision has to be reversed. What is not kept: the content rows, because
# those are the problem being solved.
#
# Three phases, and each one has to be asked for. This script never proceeds
# from one to the next on its own.
#
#   bash deploy/rebuild-mostafaei.sh              1. back up, verify, stop
#   bash deploy/rebuild-mostafaei.sh --wipe       2. tear down, refuses without 1
#   bash deploy/rebuild-mostafaei.sh --restore    3. media back, then verify
#
# The reinstall between 2 and 3 is a separate command, printed at the end of
# phase 2, because it is the one that wants reading before it is run.
#
set -uo pipefail

SYSUSER=mostafaei
DOMAIN=mostafaei.com
APP_DIR="/home/${SYSUSER}/public_html/backend"
DB_NAME="${SYSUSER}_db"
DB_USER="${SYSUSER}_app"
VAULT="/root/mostafaei-rebuild"
MODE="${1:-backup}"

say()  { printf '\n════ %s ════════════════════════════\n' "$1"; }
ok()   { printf '  ok    %s\n' "$1"; }
bad()  { printf '  FAIL  %s\n' "$1"; }

# A backup is only a backup once it has been looked at. Every file this
# produces is checked for a plausible size before the next step is allowed,
# because an empty dump and a good dump look identical in a directory listing.
verify_vault() {
    local stamp="$1" fail=0 f sz
    for f in db.sql media.tar.gz templates.tar.gz; do
        if [ ! -s "${VAULT}/${stamp}/${f}" ]; then
            bad "${f} missing or empty"; fail=1; continue
        fi
        sz=$(du -h "${VAULT}/${stamp}/${f}" | cut -f1)
        ok "${f}  ${sz}"
    done
    # A pg_dump of a live site is tens of thousands of lines. A few hundred
    # means it connected, found nothing, and exited 0.
    local lines
    lines=$(wc -l < "${VAULT}/${stamp}/db.sql" 2>/dev/null || echo 0)
    if [ "$lines" -lt 500 ]; then
        bad "db.sql is only ${lines} lines, that is not a whole site"; fail=1
    else
        ok "db.sql  ${lines} lines"
    fi
    return "$fail"
}

# ─────────────────────────────────────────────────────────────────────────────
if [ "$MODE" = "backup" ]; then
    say "1. Backing up ${DOMAIN}"
    STAMP=$(date +%F-%H%M)
    mkdir -p "${VAULT}/${STAMP}"

    echo "  → database"
    sudo -u postgres pg_dump "$DB_NAME" > "${VAULT}/${STAMP}/db.sql" 2>"${VAULT}/${STAMP}/db.err"
    [ -s "${VAULT}/${STAMP}/db.err" ] && cat "${VAULT}/${STAMP}/db.err"

    echo "  → media"
    tar czf "${VAULT}/${STAMP}/media.tar.gz" -C "$APP_DIR" media 2>/dev/null

    echo "  → templates"
    tar czf "${VAULT}/${STAMP}/templates.tar.gz" -C "$APP_DIR" templates 2>/dev/null

    echo "  → env and unit"
    \cp -f "${APP_DIR}/.env" "${VAULT}/${STAMP}/env.txt" 2>/dev/null
    \cp -f "/etc/systemd/system/${SYSUSER}.service" "${VAULT}/${STAMP}/" 2>/dev/null

    say "Checking the backup is real"
    if verify_vault "$STAMP"; then
        echo "$STAMP" > "${VAULT}/VERIFIED"
        chmod -R go-rwx "$VAULT"
        say "Kept at ${VAULT}/${STAMP}"
        cat <<NOTE
  Nothing has been changed or removed. The site is still running.

  Note what the dump is for. Restoring it would put back the content rows
  that carry Final Target's name, which is the thing being fixed, so it is
  a way back if this turns out wrong, not the plan.

  Read this before phase 2, it is the only part that matters:

    A blank install has no pages. The homepage, the portfolio and the
    written content on ${DOMAIN} do not come back by themselves. The
    images do, and the dump above holds the text if any of it is worth
    typing back in.

  If that is understood and wanted:
    bash deploy/rebuild-mostafaei.sh --wipe
NOTE
        exit 0
    fi
    say "Backup failed its own check. Nothing else will run."
    exit 1
fi

# ─────────────────────────────────────────────────────────────────────────────
if [ "$MODE" = "--wipe" ]; then
    say "2. Tearing down ${DOMAIN}"

    if [ ! -f "${VAULT}/VERIFIED" ]; then
        bad "no verified backup. Run this with no arguments first."
        exit 1
    fi
    STAMP=$(cat "${VAULT}/VERIFIED")
    echo "  Backup on record: ${VAULT}/${STAMP}"
    verify_vault "$STAMP" || { bad "the recorded backup no longer checks out"; exit 1; }

    echo
    read -r -p "  Type the domain to confirm: " typed
    [ "$typed" = "$DOMAIN" ] || { echo "  Stopped."; exit 1; }

    echo
    echo "  → stopping the service"
    systemctl stop "$SYSUSER" 2>/dev/null
    systemctl disable "$SYSUSER" 2>/dev/null
    \rm -f "/etc/systemd/system/${SYSUSER}.service"
    systemctl daemon-reload

    echo "  → dropping the database"
    sudo -u postgres psql -v ON_ERROR_STOP=1 <<SQL
DROP DATABASE IF EXISTS ${DB_NAME};
DROP ROLE IF EXISTS ${DB_USER};
SQL

    # Moved, not deleted. ft-tenant-install.sh refuses to install over an
    # existing directory, which is the behaviour we want, and a move satisfies
    # it without making the old tree unrecoverable this evening.
    echo "  → moving the old tree aside"
    \mv -f "$APP_DIR" "${VAULT}/${STAMP}/backend-old"

    say "Gone. Apache and DNS untouched, so the domain still points here."
    cat <<NOTE
  The old tree is at ${VAULT}/${STAMP}/backend-old

  Now the reinstall, from The Panel and not from Final Target. Installing
  from Final Target's tree would hand this site Final Target's model
  defaults, which is how the last one came up saying Transform Your Online
  Appearance.

    cd /root/the-panel && bash deploy/null-check.sh

  It must say clean. Then, on one line:

    BUILDER_NAME="MOSTAFAEI" BUILDER_URL="https://mostafaei.com" bash /root/the-panel/deploy/ft-tenant-install.sh --yes --source /root/the-panel --name "MOSTAFAEI" --domain mostafaei.com --user mostafaei --port 8002 --plan signature --modules homepage,portfolio,insights,services,chat

  No --admin. The Super Administrator address is a fleet decision and the
  install script already holds it. Passing one here would put a different
  address on this site than on every other.

  Check the port against the old unit before running it:
    grep -i bind ${VAULT}/${STAMP}/${SYSUSER}.service

  Then:
    bash deploy/rebuild-mostafaei.sh --restore
NOTE
    exit 0
fi

# ─────────────────────────────────────────────────────────────────────────────
if [ "$MODE" = "--restore" ]; then
    say "3. Putting the images back"

    [ -f "${VAULT}/VERIFIED" ] || { bad "nothing on record to restore from"; exit 1; }
    STAMP=$(cat "${VAULT}/VERIFIED")
    [ -d "$APP_DIR" ] || { bad "$APP_DIR does not exist. Reinstall first."; exit 1; }

    tar xzf "${VAULT}/${STAMP}/media.tar.gz" -C "$APP_DIR" \
        && ok "media restored" || bad "media did not extract"
    chown -R "${SYSUSER}:${SYSUSER}" "${APP_DIR}/media"
    systemctl restart "$SYSUSER" && sleep 3

    say "Does it still say Final Target anywhere"
    printf '  service   %s\n' "$(systemctl is-active "$SYSUSER")"
    curl -s -o /dev/null -w "  site      %{http_code}\n" "https://${DOMAIN}/"
    curl -s -o /dev/null -w "  panel     %{http_code}\n" "https://panel.${DOMAIN}/"

    total=0
    for path in / /terms/ /privacy-policy/ /contact/; do
        n=$(curl -s "https://${DOMAIN}${path}" | grep -oiE "final target|finaltarget" | wc -l)
        total=$((total + n))
        printf '  %-18s %s mention(s)\n' "$path" "$n"
    done
    echo
    if [ "$total" -eq 0 ]; then
        ok "the public site does not name Final Target"
    else
        bad "${total} still there. They are template literals, not data."
    fi

    # The sidebar was the other half of the report: it read FT Panel and fell
    # back to Final Target's logo file whenever a tenant had no logo of its own.
    say "The panel sidebar"
    grep -c "logo_FT\|FT Panel" "${APP_DIR}/templates/cms/base.html" 2>/dev/null \
        | grep -q '^0$' && ok "no FT markers in base.html" || bad "base.html still carries one"

    say "What is left to you"
    cat <<NOTE
  In the new panel at https://panel.${DOMAIN}/settings/

    Site name, logo, colours, contact details
    The homepage content, which is blank by design

  Nothing there is filled in from Final Target, on purpose. And the credit
  line at the foot of the public pages already reads MOSTAFAEI, because the
  install was given it.

  If it needs undoing:
    ${VAULT}/${STAMP}/backend-old  and  ${VAULT}/${STAMP}/db.sql
NOTE
    exit 0
fi

echo "Unknown option: ${MODE}"
echo "Use: no argument to back up, --wipe to tear down, --restore afterwards."
exit 1
