#!/usr/bin/env bash
# Backup SaaS - one-line agent installer
# Usage: curl -fsSL https://www.orathos.com/install/agent.sh | sudo BACKUP_SAAS_TOKEN=agt_xxx bash
set -eu

SERVER_URL="${BACKUP_SAAS_URL:-https://www.orathos.com}"
TOKEN="${BACKUP_SAAS_TOKEN:-}"
INSTALL_DIR="${BACKUP_SAAS_DIR:-/opt/backup-agent}"
CONFIG_DIR="/etc/backup-agent"

if [[ -z "$TOKEN" ]]; then
    echo "ERROR: BACKUP_SAAS_TOKEN env var is required." >&2
    exit 1
fi

if [[ $EUID -ne 0 ]]; then
    echo "ERROR: must run as root (use sudo)." >&2
    exit 1
fi

echo "==> Installing dependencies"
if command -v apt-get >/dev/null; then
    apt-get update -y >/dev/null
    apt-get install -y python3 python3-pip python3-venv curl ca-certificates
elif command -v dnf >/dev/null; then
    dnf install -y python3 python3-pip curl ca-certificates
elif command -v yum >/dev/null; then
    yum install -y python3 python3-pip curl ca-certificates
else
    echo "WARN: unknown package manager; ensure python3 + pip are installed." >&2
fi

echo "==> Setting up $INSTALL_DIR"
mkdir -p "$INSTALL_DIR" "$CONFIG_DIR"

python3 -m venv "$INSTALL_DIR/venv"
"$INSTALL_DIR/venv/bin/pip" install --upgrade pip >/dev/null
"$INSTALL_DIR/venv/bin/pip" install requests cryptography zstandard >/dev/null

echo "==> Downloading agent code"
curl -fsSL "$SERVER_URL/install/agent.tar.gz" -o /tmp/agent.tar.gz
tar -xzf /tmp/agent.tar.gz -C "$INSTALL_DIR"
rm -f /tmp/agent.tar.gz

echo "==> Writing config"
cat > "$CONFIG_DIR/config.toml" <<EOF
server_url = "$SERVER_URL"
token      = "$TOKEN"

include    = ["/var/www", "/home"]
exclude    = ["node_modules", "vendor/cache", "*.log", "*.tmp", ".git"]
chunk_size = 4194304
EOF
chmod 600 "$CONFIG_DIR/config.toml"

echo "==> Installing systemd unit"
cat > /etc/systemd/system/backup-agent.service <<EOF
[Unit]
Description=Backup SaaS Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=root
WorkingDirectory=$INSTALL_DIR
Environment=PATH=$INSTALL_DIR/venv/bin:/usr/bin:/bin
ExecStart=$INSTALL_DIR/venv/bin/python -m agent --config $CONFIG_DIR/config.toml run-backup --type incremental
Restart=on-failure
RestartSec=30

[Install]
WantedBy=multi-user.target
EOF

cat > /etc/systemd/system/backup-agent.timer <<EOF
[Unit]
Description=Run Backup SaaS Agent backup hourly

[Timer]
OnCalendar=hourly
Persistent=true
RandomizedDelaySec=600

[Install]
WantedBy=timers.target
EOF

systemctl daemon-reload
systemctl enable --now backup-agent.timer

cat > /etc/systemd/system/backup-agent-heartbeat.service <<EOF
[Unit]
Description=Backup SaaS Agent heartbeat
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
User=root
WorkingDirectory=$INSTALL_DIR
Environment=PATH=$INSTALL_DIR/venv/bin:/usr/bin:/bin
ExecStart=$INSTALL_DIR/venv/bin/python -m agent --config $CONFIG_DIR/config.toml heartbeat
EOF

cat > /etc/systemd/system/backup-agent-heartbeat.timer <<EOF
[Unit]
Description=Backup SaaS Agent heartbeat every 5 minutes

[Timer]
OnCalendar=*:0/5
Persistent=true
RandomizedDelaySec=30

[Install]
WantedBy=timers.target
EOF

systemctl daemon-reload
systemctl enable --now backup-agent-heartbeat.timer

cat > /etc/systemd/system/backup-agent-poll.service <<EOF
[Unit]
Description=Backup SaaS Agent — poll for pending backups
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
User=root
WorkingDirectory=$INSTALL_DIR
Environment=PATH=$INSTALL_DIR/venv/bin:/usr/bin:/bin
ExecStart=$INSTALL_DIR/venv/bin/python -m agent --config $CONFIG_DIR/config.toml run-backup --type incremental
EOF

cat > /etc/systemd/system/backup-agent-poll.timer <<EOF
[Unit]
Description=Backup SaaS Agent — poll every 1 minute(s)

[Timer]
OnCalendar=*:0/1
Persistent=true
RandomizedDelaySec=20

[Install]
WantedBy=timers.target
EOF

systemctl daemon-reload
systemctl enable --now backup-agent-poll.timer

echo "==> Running handshake"
cd "$INSTALL_DIR"
if ! "$INSTALL_DIR/venv/bin/python" -m agent --config "$CONFIG_DIR/config.toml" handshake; then
    echo "WARN: handshake failed" >&2
fi
"$INSTALL_DIR/venv/bin/python" -m agent --config "$CONFIG_DIR/config.toml" heartbeat >/dev/null 2>&1 || true
"$INSTALL_DIR/venv/bin/python" -m agent --config "$CONFIG_DIR/config.toml" run-backup --type incremental >/dev/null 2>&1 || true

echo
echo "✓ Backup SaaS agent installed."
echo "  Logs:        journalctl -u backup-agent -f"
echo "  Run manually: $INSTALL_DIR/venv/bin/python -m agent --config $CONFIG_DIR/config.toml run-backup --type full"