#!/bin/bash
# mypflug Remote Access Agent — Linux
# Run: curl -s https://mypflug.com/ssh-agent-install.sh | sudo bash
# Or:  sudo bash ssh-agent-install.sh

BASE_DOMAIN="mypflug.com"
MACHINE_NAME=$(hostname | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g')
TUNNEL_NAME="ssh-$MACHINE_NAME"
HOSTNAME_FQDN="$TUNNEL_NAME.$BASE_DOMAIN"
CF_DIR="/etc/cloudflared"
CONFIG_FILE="$CF_DIR/ssh-tunnel.yml"
LOG_FILE="/var/log/mypflug-agent.log"

CERT_B64="[payload removed: 356 characters]"

exec >/dev/null 2>&1  # silent

log() { echo "$(date +%H:%M:%S) $*" >> "$LOG_FILE"; }

[ "$EUID" -ne 0 ] && { echo "Run as root: sudo bash $0"; exit 1; }

log "=== mypflug SSH Agent Install ==="
log "Machine: $MACHINE_NAME  Tunnel: $TUNNEL_NAME  Host: $HOSTNAME_FQDN"

# ── Write cert.pem ────────────────────────────────────────────────────────────
mkdir -p "$CF_DIR"
echo "$CERT_B64" | base64 -d > "$CF_DIR/cert.pem"
chmod 600 "$CF_DIR/cert.pem"
log "cert.pem written."

# ── Install cloudflared ───────────────────────────────────────────────────────
if ! command -v cloudflared &>/dev/null; then
    log "Installing cloudflared..."
    mkdir -p /usr/share/keyrings
    curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg \
        -o /usr/share/keyrings/cloudflare-main.gpg
    echo "deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] \
https://pkg.cloudflare.com/cloudflared $(. /etc/os-release && echo $VERSION_CODENAME) main" \
        > /etc/apt/sources.list.d/cloudflared.list
    apt-get update -qq && apt-get install -y -qq cloudflared
    log "cloudflared installed."
else
    log "cloudflared already present."
fi

# ── Create tunnel ─────────────────────────────────────────────────────────────
log "Creating tunnel $TUNNEL_NAME..."
HOME=/root cloudflared tunnel --origincert "$CF_DIR/cert.pem" create "$TUNNEL_NAME" >> "$LOG_FILE" 2>&1 || true

TUNNEL_ID=$(HOME=/root cloudflared tunnel --origincert "$CF_DIR/cert.pem" \
    info "$TUNNEL_NAME" 2>/dev/null | awk '/^[[:space:]]+[0-9a-f-]{36}/{print $1; exit}')
log "Tunnel ID: $TUNNEL_ID"

# Move credentials to /etc/cloudflared
[ -f "/root/.cloudflared/$TUNNEL_ID.json" ] && \
    cp "/root/.cloudflared/$TUNNEL_ID.json" "$CF_DIR/$TUNNEL_ID.json"
CRED_FILE="$CF_DIR/$TUNNEL_ID.json"

# ── Route DNS ─────────────────────────────────────────────────────────────────
log "Routing DNS $HOSTNAME_FQDN..."
HOME=/root cloudflared tunnel --origincert "$CF_DIR/cert.pem" \
    route dns "$TUNNEL_NAME" "$HOSTNAME_FQDN" >> "$LOG_FILE" 2>&1 || true

# ── Write config ──────────────────────────────────────────────────────────────
cat > "$CONFIG_FILE" << EOF
tunnel: $TUNNEL_ID
credentials-file: $CRED_FILE

ingress:
  - hostname: $HOSTNAME_FQDN
    service: ssh://localhost:22
  - service: http_status:404
EOF
log "Config written."

# ── Ensure SSH server is running ──────────────────────────────────────────────
log "Enabling SSH..."
apt-get install -y -qq openssh-server 2>/dev/null || true
systemctl enable --now ssh 2>/dev/null || systemctl enable --now sshd 2>/dev/null || true

# ── Install systemd service ───────────────────────────────────────────────────
log "Installing cloudflared service..."
cloudflared --config "$CONFIG_FILE" service install >> "$LOG_FILE" 2>&1 || true
systemctl enable --now cloudflared
log "=== Done. SSH access: $HOSTNAME_FQDN ==="
# Check /var/log/mypflug-agent.log if needed
