#!/usr/bin/env bash
# turbgate — instalador Linux 1-liner.
#
# Uso:
#   curl -fsSL https://turbgate.botbox.info/install.sh | sudo bash -s -- <cliente_id>
#
# O que faz:
#   1. detecta arch (amd64/arm64)
#   2. baixa o .deb mais recente do mirror
#   3. apt install
#   4. faz POST no ERP pra obter cert mTLS
#   5. grava /etc/turbgate/{cert,key,ca}.pem + turbgate.yaml
#   6. systemctl enable --now turbgate
set -euo pipefail

MIRROR="${TURBGATE_MIRROR:-https://turbgate.botbox.info}"
SERVER_ADDR="${TURBGATE_SERVER_ADDR:-turbgate.botbox.info:7000}"
ERP_BASE_URL="${TURBGATE_ERP_BASE_URL:-https://www.seucondominio.com.br}"

cliente_id="${1:-}"
if [[ -z "$cliente_id" ]]; then
    echo "uso: $0 <cliente_id>" >&2
    exit 2
fi

if [[ $EUID -ne 0 ]]; then
    echo "este script precisa rodar como root (sudo)." >&2
    exit 1
fi

# 1. detect arch
case "$(uname -m)" in
    x86_64|amd64)  arch=amd64 ;;
    aarch64|arm64) arch=arm64 ;;
    *) echo "arquitetura não suportada: $(uname -m)" >&2; exit 1 ;;
esac
echo "→ arch detectado: $arch"

# 2. depende de curl + jq (apt já tá disponível)
if ! command -v curl >/dev/null; then
    apt-get update -qq && apt-get install -y -qq curl
fi
if ! command -v jq >/dev/null; then
    apt-get update -qq && apt-get install -y -qq jq
fi

# 3. baixar e instalar .deb
deb_url="${MIRROR}/turbgate_${arch}.deb"
tmp_deb=$(mktemp --suffix=.deb)
echo "→ baixando $deb_url"
curl -fsSL -o "$tmp_deb" "$deb_url"
echo "→ instalando .deb"
apt-get install -y -qq "$tmp_deb"
rm -f "$tmp_deb"

# 4. obter cert mTLS via ERP (endpoint público, sem token — protegido por rate limit no servidor)
echo "→ pedindo cert mTLS pro ERP (cliente_id=$cliente_id)"
resp=$(curl -fsSL -X POST "${ERP_BASE_URL}/portarias/issue_tunnel_cert.json" \
    -H "Content-Type: application/json" \
    -d "{\"cliente_id\":${cliente_id}}")

# 5. gravar artefatos
install -d -m 0700 /etc/turbgate
echo "$resp" | jq -r '.ca_pem'   > /etc/turbgate/ca.pem
echo "$resp" | jq -r '.cert_pem' > /etc/turbgate/cert.pem
echo "$resp" | jq -r '.key_pem'  > /etc/turbgate/key.pem
chmod 0600 /etc/turbgate/{ca,cert,key}.pem

server_addr=$(echo "$resp" | jq -r '.server_addr // empty')
[[ -z "$server_addr" ]] && server_addr="$SERVER_ADDR"

# erp_token vem do response (server.salt) — cliente usa em get/update_tunnel_devices
erp_token=$(echo "$resp" | jq -r '.erp_token // empty')
if [[ -z "$erp_token" ]]; then
    echo "ERRO: ERP não retornou erp_token. Verifique PORTARIA_SERVER_SALT no Rails." >&2
    exit 1
fi

cat > /etc/turbgate/turbgate.yaml <<EOF
server_addr: ${server_addr}
cliente_id: ${cliente_id}
cert_file: /etc/turbgate/cert.pem
key_file: /etc/turbgate/key.pem
ca_file: /etc/turbgate/ca.pem
erp_base_url: ${ERP_BASE_URL}
erp_token: ${erp_token}
state_dir: /var/lib/turbgate
log_level: info
EOF
chmod 0600 /etc/turbgate/turbgate.yaml

# 6. enable + restart (restart força reload do yaml/cert se já estava rodando — idempotente em re-install/re-enroll)
systemctl daemon-reload
systemctl enable turbgate.service >/dev/null 2>&1
systemctl restart turbgate.service
sleep 2
systemctl status turbgate.service --no-pager | head -10

## 7. desabilitar sctunnel velho se presente (idempotente)
disable_old_sctunnel() {
    local found=0

    # v1 (raiz do sctunnel_client) — cron + ssh -N -R diretos
    if [ -d /var/lib/sctunnel_client ]; then
        echo "→ desabilitando sctunnel v1 (/var/lib/sctunnel_client)"
        if [ -x /var/lib/sctunnel_client/install.sh ]; then
            bash /var/lib/sctunnel_client/install.sh --remove_crons >/dev/null 2>&1 || true
        fi
        # remove crons que possam ter ficado pra trás
        crontab -l 2>/dev/null | grep -v -E "/var/lib/sctunnel_client|/opt/sctunnel" | crontab - 2>/dev/null || true
        found=1
    fi

    # v2 (/opt/sctunnel) — run.sh chamado pelo cron como root
    if [ -d /opt/sctunnel ]; then
        echo "→ desabilitando sctunnel v2 (/opt/sctunnel)"
        crontab -l 2>/dev/null | grep -v "/opt/sctunnel/" | crontab - 2>/dev/null || true
        found=1
    fi

    if [ "$found" = "1" ]; then
        # mata túneis SSH residuais (sctunnel sempre usou 'ssh -N -R')
        pkill -f "ssh -N -R" >/dev/null 2>&1 || true
        sleep 1
        local restantes
        restantes=$(pgrep -fc "ssh -N -R" 2>/dev/null || echo 0)
        echo "→ ssh -N -R residuais: ${restantes}"
        echo "  (arquivos preservados em /var/lib/sctunnel_client e /opt/sctunnel pra rollback)"
    fi
}
disable_old_sctunnel

echo
echo "✓ turbgate instalado. cliente_id=${cliente_id} → ${server_addr}"
echo "  logs:    journalctl -u turbgate -f"
echo "  status:  turbgate status"
echo "  rollback (caso necessário):  apt remove turbgate; bash /var/lib/sctunnel_client/install.sh --install_crons"
