#!/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

# ---------------------------------------------------------------------------
# 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
