import { DOKPLOY_INSTALL_URL, DOKPLOY_PORT } from "../constants.js";
import { sharedHealthCheck, sharedUpdate, sharedGetStatus, sharedCreateBackup, sharedRestoreBackup } from "./shared.js";
// Download-then-execute with script validation — private to dokploy adapter
const SCRIPT_VALIDATE = 'head -c2 "$1" | grep -q "#!" && [ "$(wc -c < "$1")" -gt 100 ]';
const DOKPLOY_UPDATE_CMD = `curl -sSL ${DOKPLOY_INSTALL_URL} -o /tmp/dokploy-install.sh && ${SCRIPT_VALIDATE.replace(/\$1/g, "/tmp/dokploy-install.sh")} && sh /tmp/dokploy-install.sh update && rm -f /tmp/dokploy-install.sh`;
export class DokployAdapter {
    name = "dokploy";
    port = DOKPLOY_PORT;
    defaultLogService = "dokploy";
    platformPorts = [80, 443, DOKPLOY_PORT];
    getCloudInit(serverName, sshPublicKey) {
        const safeName = serverName.replace(/[^a-z0-9-]/g, "");
        return `#!/bin/bash
set +e
export DEBIAN_FRONTEND=noninteractive
touch /var/log/kastell-install.log
chmod 600 /var/log/kastell-install.log
exec > >(tee /var/log/kastell-install.log) 2>&1

echo "=================================="
echo "Kastell Auto-Installer"
echo "Server: ${safeName}"
echo "Platform: Dokploy"
echo "=================================="

# Wait for network connectivity
echo "Waiting for network connectivity..."
MAX_ATTEMPTS=30
ATTEMPTS=0
while [ $ATTEMPTS -lt $MAX_ATTEMPTS ]; do
  if curl -s --max-time 5 https://dokploy.com > /dev/null 2>&1; then
    echo "Network is ready!"
    break
  fi
  ATTEMPTS=$((ATTEMPTS + 1))
  echo "Network not ready (attempt $ATTEMPTS/$MAX_ATTEMPTS)..."
  sleep 2
done

# Disable needrestart to prevent interactive prompts during Docker/package installation
echo "Disabling needrestart..."
if dpkg -l needrestart > /dev/null 2>&1; then
  apt-get remove -y needrestart || true
fi
export NEEDRESTART_MODE=a
export NEEDRESTART_SUSPEND=1

# Update system
echo "Updating system packages..."
apt-get update -y

# Configure firewall BEFORE installer (prevents SSH lockout if installer hangs)
echo "Configuring firewall..."
if command -v ufw &> /dev/null; then
  ufw allow 22/tcp
  ufw allow 80/tcp
  ufw allow 443/tcp
  ufw allow 3000/tcp
  ufw allow 2377/tcp
  ufw allow 7946/tcp
  ufw allow 7946/udp
  ufw allow 4789/udp
  echo "y" | ufw enable || true
else
  iptables -A INPUT -p tcp --dport 3000 -j ACCEPT
  iptables -A INPUT -p tcp --dport 22 -j ACCEPT
  iptables -A INPUT -p tcp --dport 80 -j ACCEPT
  iptables -A INPUT -p tcp --dport 443 -j ACCEPT
  iptables -A INPUT -p tcp --dport 2377 -j ACCEPT
  iptables -A INPUT -p tcp --dport 7946 -j ACCEPT
  iptables -A INPUT -p udp --dport 7946 -j ACCEPT
  iptables -A INPUT -p udp --dport 4789 -j ACCEPT
  iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
  mkdir -p /etc/iptables
  iptables-save > /etc/iptables/rules.v4 || true
  apt-get install -y iptables-persistent || true
fi

# Switch from socket activation to traditional SSH service (prevents Ubuntu 24.04 ssh.socket bugs)
echo "Switching to traditional SSH service..."
systemctl disable --now ssh.socket 2>/dev/null || true
systemctl enable --now ssh.service 2>/dev/null || true

# Install Dokploy
echo "Installing Dokploy..."
curl -sSL https://dokploy.com/install.sh -o /tmp/dokploy-install.sh && head -c2 /tmp/dokploy-install.sh | grep -q "#!" && [ "$(wc -c < /tmp/dokploy-install.sh)" -gt 100 ] && env DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a NEEDRESTART_SUSPEND=1 sh /tmp/dokploy-install.sh && rm -f /tmp/dokploy-install.sh

# Ensure SSH remains accessible after installation
echo "Ensuring SSH service is active..."
if ! ss -tlnp | grep -q ':22 '; then
  systemctl restart ssh.service 2>/dev/null || systemctl restart sshd.service 2>/dev/null || true
  sleep 2
fi

# Re-inject SSH public key (platform installer may overwrite authorized_keys)
${sshPublicKey ? `echo "Re-injecting SSH public key..."
mkdir -p /root/.ssh
chmod 700 /root/.ssh
grep -qF '${sshPublicKey.trim().replace(/'/g, "'\\''")}' /root/.ssh/authorized_keys 2>/dev/null || echo '${sshPublicKey.trim().replace(/'/g, "'\\''")}' >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys` : "# No SSH public key provided — skipping re-injection"}

# Wait for services
echo "Waiting for Dokploy services to start..."
sleep 30

echo "=================================="
echo "Dokploy installation completed!"
echo "=================================="
echo ""
echo "Please wait 3-5 more minutes for Dokploy to fully initialize."
echo "Then access your instance at: http://YOUR_SERVER_IP:3000"
`;
    }
    async healthCheck(ip, domain) {
        return sharedHealthCheck(ip, DOKPLOY_PORT, domain);
    }
    async createBackup(ip, serverName, provider) {
        return sharedCreateBackup(ip, serverName, provider, this.backupConfig());
    }
    async restoreBackup(ip, backupPath, manifest, options) {
        return sharedRestoreBackup(ip, backupPath, manifest, this.restoreConfig(), options);
    }
    async getStatus(ip) {
        return sharedGetStatus(ip, this.versionCmd(), DOKPLOY_PORT);
    }
    async update(ip) {
        return sharedUpdate(ip, DOKPLOY_UPDATE_CMD);
    }
    // --- Private Config Builders ------------------------------------------------
    versionCmd() {
        return "docker inspect dokploy --format '{{.Config.Image}}' 2>/dev/null | sed 's/.*://' || echo unknown";
    }
    backupConfig() {
        return {
            platform: "dokploy",
            pgDumpCmd: "set -o pipefail && docker exec $(docker ps -qf name=dokploy-postgres --no-trunc | head -1) pg_dump -U dokploy -d dokploy | gzip > /tmp/dokploy-backup.sql.gz",
            configTarCmd: "tar czf /tmp/dokploy-config.tar.gz -C /etc/dokploy .",
            versionCmd: this.versionCmd(),
            cleanupCmd: "rm -f /tmp/dokploy-backup.sql.gz /tmp/dokploy-config.tar.gz",
            dbFileName: "dokploy-backup.sql.gz",
            configFileName: "dokploy-config.tar.gz",
        };
    }
    restoreConfig() {
        return {
            platform: "dokploy",
            stopCmd: "docker service scale dokploy=0",
            startDbCmd: "docker service scale dokploy-postgres=1 && sleep 5",
            restoreDbCmd: "gunzip -c /tmp/dokploy-backup.sql.gz | docker exec -i $(docker ps -qf name=dokploy-postgres --no-trunc | head -1) psql -U dokploy -d dokploy",
            restoreConfigCmd: "tar xzf /tmp/dokploy-config.tar.gz -C /etc/dokploy",
            startCmd: "docker service scale dokploy=1",
            cleanupCmd: "rm -f /tmp/dokploy-backup.sql.gz /tmp/dokploy-config.tar.gz",
            tryRestartCmd: "docker service scale dokploy=1",
            dbFileName: "dokploy-backup.sql.gz",
            configFileName: "dokploy-config.tar.gz",
        };
    }
}
//# sourceMappingURL=dokploy.js.map