#!/usr/bin/env bash
# =============================================================================
# DO Server Config Backup — runs on orbis (165.22.1.228)
# Backs up all critical configs/scripts to GitHub weekly
# Install: /usr/local/bin/do-server-backup
# Cron:    0 4 * * 0 /usr/local/bin/do-server-backup >> /var/log/do-server-backup.log 2>&1
# =============================================================================
set -euo pipefail

PAT="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"
REPO_URL="https://${PAT}@github.com/myronblair/do-server-config.git"
REPO_DIR="/opt/do-server-config"
LOG_PREFIX="[$(date '+%Y-%m-%d %H:%M:%S')] [orbis]"

log() { echo "$LOG_PREFIX $*"; }

# ---------------------------------------------------------------------------
# 1. Clone or update repo
# ---------------------------------------------------------------------------
if [[ -d "$REPO_DIR/.git" ]]; then
    log "Pulling latest from GitHub"
    cd "$REPO_DIR"
    git config user.email "backup@orbishosting.com"
    git config user.name  "DO Server Backup"
    git pull --rebase origin main -q || true
else
    log "Cloning repo to $REPO_DIR"
    git clone "$REPO_URL" "$REPO_DIR"
    cd "$REPO_DIR"
    git config user.email "backup@orbishosting.com"
    git config user.name  "DO Server Backup"
fi

cd "$REPO_DIR"
mkdir -p scripts systemd wireguard network cron ssh ols-vhosts mysql infra

# ---------------------------------------------------------------------------
# 2. Custom scripts from /usr/local/bin (text only — skip large binaries)
# ---------------------------------------------------------------------------
log "Backing up custom scripts"
for f in /usr/local/bin/jarvis-*.sh \
          /usr/local/bin/jarvis-*.py \
          /usr/local/bin/ttg-backup.sh \
          /usr/local/bin/do-server-backup; do
    [[ -f "$f" ]] || continue
    size=$(stat -c%s "$f" 2>/dev/null || echo 0)
    [[ $size -lt 524288 ]] && cp "$f" scripts/ || log "  SKIP (too large): $f"
done
# composer is a stock PHP tool — skip it

# ---------------------------------------------------------------------------
# 3. Custom systemd service units (skip stock DO/system units)
# ---------------------------------------------------------------------------
log "Backing up custom systemd units"
CUSTOM_UNITS="jarvis-agent.service fastapi_ssh_server.service"
for unit in $CUSTOM_UNITS; do
    src="/etc/systemd/system/$unit"
    [[ -f "$src" ]] && cp "$src" systemd/ || true
done

# ---------------------------------------------------------------------------
# 4. WireGuard configs (includes private keys — repo is private)
# ---------------------------------------------------------------------------
log "Backing up WireGuard configs"
for f in /etc/wireguard/*.conf; do
    [[ -f "$f" ]] && cp "$f" wireguard/ || true
done

# ---------------------------------------------------------------------------
# 5. Network / netplan
# ---------------------------------------------------------------------------
log "Backing up netplan"
for f in /etc/netplan/*.yaml; do
    [[ -f "$f" ]] && cp "$f" network/ || true
done
cp /etc/hosts network/hosts 2>/dev/null || true
cp /etc/hostname network/hostname 2>/dev/null || true

# ---------------------------------------------------------------------------
# 6. Root crontab — custom entries only (strip CyberPanel boilerplate)
# ---------------------------------------------------------------------------
log "Backing up crontab"
crontab -l 2>/dev/null | grep -v "^#\|CyberCP\|acme.sh\|cleansessions\|run_scheduled_scans\|pdnsHealthCheck\|findBWUsage\|postfixSenderPolicy\|upgradeCritical\|renew\.py\|IncScheduler\|e2scrub\|imunify\|sessionclean\|lsws\b" \
    | sed '/^[[:space:]]*$/d' > cron/root_custom
# Also keep the full crontab for reference
crontab -l 2>/dev/null > cron/root_full || echo "# no crontab" > cron/root_full

# ---------------------------------------------------------------------------
# 7. SSH authorized_keys
# ---------------------------------------------------------------------------
log "Backing up SSH keys"
[[ -f /root/.ssh/authorized_keys ]] && cp /root/.ssh/authorized_keys ssh/ || true
[[ -f /root/.ssh/id_rsa.pub ]]      && cp /root/.ssh/id_rsa.pub ssh/      || true

# ---------------------------------------------------------------------------
# 8. OpenLiteSpeed vhost configs (CyberPanel-managed)
# ---------------------------------------------------------------------------
log "Backing up OLS vhost configs"
for vdir in /usr/local/lsws/conf/vhosts/*/; do
    vname=$(basename "$vdir")
    [[ "$vname" == "Example" ]] && continue
    mkdir -p "ols-vhosts/$vname"
    for conf in "$vdir"*.conf; do
        [[ -f "$conf" ]] && cp "$conf" "ols-vhosts/$vname/" || true
    done
done
# OLS main listener/vhost mapping
grep -E "^\s*(listener|virtualHost|address |map |vhRoot|vhDomain|configFile)" \
    /usr/local/lsws/conf/httpd_config.conf 2>/dev/null > ols-vhosts/httpd_vhosts_summary.txt || true

# ---------------------------------------------------------------------------
# 9. MySQL root credentials file
# ---------------------------------------------------------------------------
log "Backing up MySQL credentials"
[[ -f /root/.my.cnf ]] && cp /root/.my.cnf mysql/my.cnf || true
# Document all databases
mysql -e "SHOW DATABASES;" 2>/dev/null | grep -v "^Database\|information_schema\|performance_schema\|sys" > mysql/databases.txt || true

# ---------------------------------------------------------------------------
# 9b. Actual database dumps — added 2026-07-07. Previously this only wrote a
#     list of database NAMES (mysql/databases.txt above), never the data
#     itself. If this server were lost, every site's real data — orders,
#     accounts, bookings — would be gone even though the backup "succeeded"
#     every week. Dumps every real business DB (skips cyberpanel's own
#     internal DB and MySQL system schemas).
# ---------------------------------------------------------------------------
log "Dumping site databases"
mkdir -p databases
for db in $(mysql -N -e "SHOW DATABASES;" 2>/dev/null | grep -vE "^(information_schema|performance_schema|mysql|sys|cyberpanel)$"); do
    if mysqldump --single-transaction --routines --triggers "$db" 2>/dev/null | gzip > "databases/${db}.sql.gz"; then
        SIZE=$(du -sh "databases/${db}.sql.gz" | cut -f1)
        log "  $db -> ${db}.sql.gz ($SIZE)"
    else
        log "  ERROR dumping $db"
        rm -f "databases/${db}.sql.gz"
    fi
done

# ---------------------------------------------------------------------------
# 9c. Actual website files — added 2026-07-07. Same gap as above: the config
#     backup only ever documented site names + disk usage (site-list.txt
#     below), never copied the files themselves. .git is excluded per site
#     since each site's own repo (on GitHub, mirrored to Gitea) already
#     covers code history — this is a content/uploads/config safety net for
#     whatever isn't (or hasn't yet been) committed there.
# ---------------------------------------------------------------------------
log "Backing up website files"
mkdir -p sites
for d in /home/*/public_html; do
    site=$(basename "$(dirname "$d")")
    mkdir -p "sites/$site"
    rsync -a --delete --exclude='.git' "$d/" "sites/$site/public_html/"
done

# ---------------------------------------------------------------------------
# 10. /opt/infra snapshot (already a separate git repo — copy contents)
# ---------------------------------------------------------------------------
log "Backing up /opt/infra snapshot"
if [[ -d /opt/infra ]]; then
    rsync -a --exclude='.git' /opt/infra/ infra/
fi

# SMTP config docs
if [[ -d /opt/smtp-for-websites ]]; then
    mkdir -p smtp-docs
    rsync -a --exclude='.git' /opt/smtp-for-websites/ smtp-docs/
fi

# ---------------------------------------------------------------------------
# 11. CyberPanel website list (for documentation)
# ---------------------------------------------------------------------------
log "Documenting website list"
{
    echo "# Websites on DO server — $(date '+%Y-%m-%d')"
    echo ""
    for d in /home/*/public_html; do
        site=$(echo "$d" | sed 's|/home/||;s|/public_html||')
        diskuse=$(du -sh "$d" 2>/dev/null | cut -f1)
        echo "- $site  ($diskuse)"
    done
} > ols-vhosts/site-list.txt

# ---------------------------------------------------------------------------
# 12. Commit and push
# ---------------------------------------------------------------------------
log "Committing changes"
git add -A
if git diff --cached --quiet; then
    log "No changes to commit"
else
    CHANGES=$(git diff --cached --stat | tail -1)
    git commit -m "[orbis] Weekly backup $(date '+%Y-%m-%d') — $CHANGES"
    log "Pushing to GitHub"
    git push origin main
    log "Backup complete"
fi

# ---------------------------------------------------------------------------
# 13. Zip snapshot for direct download — added 2026-07-07. Requested so the
#     full backup (sites + database dumps + configs) can be downloaded
#     straight from JARVIS's admin panel (Blair HQ), not just pulled via git.
#     Regenerated unconditionally every run (even if nothing changed) so its
#     own file timestamp always reflects when the backup last actually ran.
#     Lives outside the git repo dir so it's never accidentally committed.
# ---------------------------------------------------------------------------
log "Creating downloadable zip snapshot"
ZIP_TMP="/opt/do-server-backup.zip.tmp"
ZIP_FINAL="/opt/do-server-backup.zip"
rm -f "$ZIP_TMP"
(cd "$REPO_DIR" && zip -rq "$ZIP_TMP" . -x '.git/*')
mv "$ZIP_TMP" "$ZIP_FINAL"
ZIPSIZE=$(du -sh "$ZIP_FINAL" | cut -f1)
log "Zip snapshot ready: $ZIP_FINAL ($ZIPSIZE)"
