#!/bin/bash
# =====================================================================
#  DFCode Suporte Remoto - instalador da CENTRAL (VPS Linux)
#  Uso (como root):   bash instalar-central.sh
# =====================================================================
set -e

DESTINO=/opt/dfcode-central
SERVICO=dfcode-central
PORTA_PADRAO=5960

verde()   { echo -e "\e[32m$*\e[0m"; }
amarelo() { echo -e "\e[33m$*\e[0m"; }
vermelho(){ echo -e "\e[31m$*\e[0m"; }

if [ "$(id -u)" != "0" ]; then
    vermelho "Rode como root (ou com sudo)."
    exit 1
fi

ORIGEM="$(cd "$(dirname "$0")" && pwd)"
if [ ! -f "$ORIGEM/central.py" ]; then
    vermelho "central.py nao encontrado ao lado deste script."
    exit 1
fi

echo
verde "=== Instalando a Central DFCode Suporte Remoto ==="
echo

# ---------- Python 3 ----------
if ! command -v python3 >/dev/null 2>&1; then
    amarelo "Instalando Python 3..."
    if command -v dnf >/dev/null; then dnf install -y python3
    elif command -v yum >/dev/null; then yum install -y python3
    elif command -v apt-get >/dev/null; then apt-get update && apt-get install -y python3
    else vermelho "Instale o python3 manualmente e rode de novo."; exit 1; fi
fi
python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3,6) else 1)' || {
    vermelho "Python 3.6 ou mais novo e necessario."; exit 1; }
command -v openssl >/dev/null || {
    if command -v dnf >/dev/null; then dnf install -y openssl
    elif command -v yum >/dev/null; then yum install -y openssl
    else apt-get install -y openssl; fi
}

# ---------- Perguntas ----------
CONF_EXISTE=0
[ -f "$DESTINO/central.conf" ] && CONF_EXISTE=1

if [ $CONF_EXISTE = 1 ]; then
    PORTA=$(grep -E '^porta=' "$DESTINO/central.conf" | cut -d= -f2)
    PORTA=${PORTA:-$PORTA_PADRAO}
    amarelo "Instalacao anterior encontrada: mantendo porta $PORTA, certificado e dados."
else
    read -r -p "Dominio da central (ex.: suporte.dfcode.com.br): " DOMINIO
    DOMINIO=${DOMINIO:-central}
    read -r -p "Porta da central [$PORTA_PADRAO]: " PORTA
    PORTA=${PORTA:-$PORTA_PADRAO}
fi

# ---------- Arquivos ----------
mkdir -p "$DESTINO/dados"
cp "$ORIGEM/central.py" "$DESTINO/central.py"
chmod 750 "$DESTINO"
chmod 700 "$DESTINO/dados"

if [ $CONF_EXISTE = 0 ]; then
    cat > "$DESTINO/central.conf" <<EOF
# Configuracao da central DFCode
porta=$PORTA
certificado=certificado.pem
chave=chave.pem
EOF
fi

# ---------- Certificado (criptografia) ----------
if [ ! -f "$DESTINO/certificado.pem" ]; then
    amarelo "Gerando certificado de criptografia (valido por 20 anos)..."
    openssl req -x509 -newkey rsa:2048 -nodes -days 7300 \
        -keyout "$DESTINO/chave.pem" -out "$DESTINO/certificado.pem" \
        -subj "/CN=${DOMINIO:-central}/O=DFCode Software" >/dev/null 2>&1
    chmod 600 "$DESTINO/chave.pem"
fi
IMPRESSAO=$(openssl x509 -in "$DESTINO/certificado.pem" -noout -fingerprint -sha256 | cut -d= -f2 | tr -d ':')

# ---------- Servico (inicia sozinho com a VPS) ----------
cat > /etc/systemd/system/$SERVICO.service <<EOF
[Unit]
Description=Central DFCode Suporte Remoto
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
WorkingDirectory=$DESTINO
ExecStart=$(command -v python3) -u $DESTINO/central.py servir
Restart=always
RestartSec=3
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable $SERVICO >/dev/null 2>&1
systemctl restart $SERVICO

# ---------- Firewall ----------
if command -v csf >/dev/null 2>&1 && [ -f /etc/csf/csf.conf ]; then
    # VPS com cPanel/WHM (comum na HostGator) usa o CSF
    if ! grep -E '^TCP_IN' /etc/csf/csf.conf | grep -qw "$PORTA"; then
        sed -i -E "s/^(TCP_IN = \"[^\"]*)\"/\1,$PORTA\"/" /etc/csf/csf.conf
        csf -r >/dev/null 2>&1 || true
    fi
    verde "[ok] Porta $PORTA liberada no CSF"
elif command -v firewall-cmd >/dev/null 2>&1 && systemctl is-active --quiet firewalld; then
    firewall-cmd --permanent --add-port=$PORTA/tcp >/dev/null
    firewall-cmd --reload >/dev/null
    verde "[ok] Porta $PORTA liberada no firewalld"
elif command -v ufw >/dev/null 2>&1 && ufw status | grep -q active; then
    ufw allow $PORTA/tcp >/dev/null
    verde "[ok] Porta $PORTA liberada no ufw"
else
    amarelo "Nenhum firewall conhecido ativo. Se houver outro, libere a porta TCP $PORTA."
fi

sleep 2
if systemctl is-active --quiet $SERVICO; then
    verde "[ok] Central rodando"
else
    vermelho "A central nao iniciou. Veja: journalctl -u $SERVICO -n 50"
    exit 1
fi

# ---------- Primeiro tecnico ----------
if [ ! -s "$DESTINO/dados/tecnicos.json" ]; then
    echo
    amarelo "Crie agora o primeiro usuario tecnico (para usar no DFCodeTecnico.exe):"
    read -r -p "Usuario: " USUARIO
    if [ -n "$USUARIO" ]; then
        (cd "$DESTINO" && python3 central.py adicionar-tecnico "$USUARIO")
    fi
fi

echo
verde "=================================================================="
verde " CENTRAL INSTALADA!"
verde "=================================================================="
echo
echo " Copie estes dados para o arquivo  config\\servidor.cfg  no Windows:"
echo
echo "    endereco=${DOMINIO:-<seu dominio>}"
echo "    porta=$PORTA"
echo "    impressao=$IMPRESSAO"
echo
echo " Comandos uteis:"
echo "    Criar tecnico : cd $DESTINO && python3 central.py adicionar-tecnico NOME"
echo "    Ver clientes  : cd $DESTINO && python3 central.py clientes"
echo "    Ver acessos   : tail -50 $DESTINO/dados/acessos.log"
echo "    Status        : systemctl status $SERVICO"
echo
