#!/bin/sh
# backup-config.sh — Weekly router config backup to fleet hub.
# Works on both Synology SRM and GL OpenWrt.
# Run via cron: 0 3 * * 0 /usr/lib/busrouter/backup-config.sh
#
# Detects platform, exports config, POSTs to hub.
# Hub stores: /backups/<DEVICE_ID>/YYYY-MM-DD-HHMM.tar.gz

set -e

# ── Platform detection ─────────────────────────────────────────────
detect_platform() {
    if [ -f /etc/synoinfo.conf ]; then
        echo "synology"
    elif [ -f /etc/openwrt_release ]; then
        echo "openwrt"
    else
        echo "unknown"
    fi
}

PLATFORM=$(detect_platform)
DEVICE_ID=$(cat /etc/busrouter/device-id 2>/dev/null || hostname 2>/dev/null || echo "unknown")

# ── Config ─────────────────────────────────────────────────────────
HUB="${BACKUP_HUB:-http://167.172.237.162:8080}"
BACKUP_DIR="/tmp/busrouter-backup"
TIMESTAMP=$(date +%Y-%m-%d-%H%M)
ARCHIVE="${BACKUP_DIR}/${DEVICE_ID}-${TIMESTAMP}.tar.gz"

mkdir -p "$BACKUP_DIR"

# ── Export platform-specific config ─────────────────────────────────
export_config() {
    case "$PLATFORM" in
        synology)
            # SRM config export via synoconfbkp
            if command -v synoconfbkp >/dev/null 2>&1; then
                synoconfbkp export --filepath "$BACKUP_DIR/synology_config.dss" 2>/dev/null || true
            fi
            # Manual: copy critical config files
            mkdir -p "$BACKUP_DIR/config"
            cp /etc/synoinfo.conf "$BACKUP_DIR/config/" 2>/dev/null || true
            cp /usr/syno/etc/synonet/wan.conf "$BACKUP_DIR/config/" 2>/dev/null || true
            cp /usr/syno/etc/synonet/lan.conf "$BACKUP_DIR/config/" 2>/dev/null || true
            cp /usr/syno/etc/wifi/*.json "$BACKUP_DIR/config/" 2>/dev/null || true
            cp /usr/syno/etc/smartwan/smartwan.conf "$BACKUP_DIR/config/" 2>/dev/null || true
            cp /etc/syno-balance/syno-balance.conf "$BACKUP_DIR/config/" 2>/dev/null || true
            cp /etc/kit-connect/connect.conf "$BACKUP_DIR/config/" 2>/dev/null || true
            cp /etc/aiwanbal/aiwanbal.conf "$BACKUP_DIR/config/" 2>/dev/null || true
            cp /etc/busrouter/device-id "$BACKUP_DIR/config/" 2>/dev/null || true
            cp /etc/busrouter/version "$BACKUP_DIR/config/" 2>/dev/null || true
            ;;

        openwrt)
            # GL OpenWrt: uci export everything
            mkdir -p "$BACKUP_DIR/config"
            uci export network  > "$BACKUP_DIR/config/network.uci"    2>/dev/null || true
            uci export wireless > "$BACKUP_DIR/config/wireless.uci"   2>/dev/null || true
            uci export firewall > "$BACKUP_DIR/config/firewall.uci"   2>/dev/null || true
            uci export mwan3    > "$BACKUP_DIR/config/mwan3.uci"      2>/dev/null || true
            uci export system   > "$BACKUP_DIR/config/system.uci"     2>/dev/null || true
            cp /etc/busrouter/device-id "$BACKUP_DIR/config/" 2>/dev/null || true
            cp /etc/busrouter/version   "$BACKUP_DIR/config/" 2>/dev/null || true
            ;;

        *)
            # Generic: grab what we can
            mkdir -p "$BACKUP_DIR/config"
            cp /etc/busrouter/device-id "$BACKUP_DIR/config/" 2>/dev/null || true
            cp /etc/busrouter/version   "$BACKUP_DIR/config/" 2>/dev/null || true
            ;;
    esac

    # Common: interface info, routes, iptables
    ip addr show > "$BACKUP_DIR/config/ip-addr.txt" 2>/dev/null || true
    ip route show > "$BACKUP_DIR/config/ip-route.txt" 2>/dev/null || true
}

# ── Package and send ───────────────────────────────────────────────
backup_and_send() {
    export_config

    # Create archive
    cd "$BACKUP_DIR" && tar czf "$ARCHIVE" config/
    local size=$(wc -c < "$ARCHIVE" 2>/dev/null || echo 0)

    logger -t busrouter "backup: ${DEVICE_ID} ${TIMESTAMP} ${size} bytes"

    # POST to hub
    local resp=""
    resp=$(curl -s --connect-timeout 30 --max-time 60 \
        -X POST \
        -F "device_id=${DEVICE_ID}" \
        -F "platform=${PLATFORM}" \
        -F "timestamp=${TIMESTAMP}" \
        -F "file=@${ARCHIVE}" \
        "${HUB}/api/backup" 2>/dev/null) || true

    if echo "$resp" | grep -q '"ok"'; then
        logger -t busrouter "backup: uploaded successfully"
    else
        logger -t busrouter "backup: upload failed (hub unreachable or error)"
    fi

    # Cleanup
    rm -rf "$BACKUP_DIR"
}

# ── Run ────────────────────────────────────────────────────────────
backup_and_send
