#!/bin/bash

#####################################################################################################
# Sistema Gerenciador de Túneis SSH Independentes
# Versão Interativa - Controle independente de múltiplos túneis
#####################################################################################################

# Cores para output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
NC='\033[0m' # No Color

# Configurações SSH
scpoptions="-o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/dev/null -o ServerAliveInterval=60 -o ServerAliveCountMax=5"

# Arquivo de configuração e estado
CONFIG_DIR="/tmp/ssh-tunnel-manager"
CONFIG_FILE="$CONFIG_DIR/config"
STATE_FILE="$CONFIG_DIR/state"
TUNNEL1_PID_FILE="$CONFIG_DIR/tunnel1.pid"
TUNNEL2_PID_FILE="$CONFIG_DIR/tunnel2.pid"

# Criar diretório se não existir
mkdir -p "$CONFIG_DIR"

# Variáveis globais
servidor1_full=""
servidor2_full=""
password_servidor2=""
porta_local_tunel1="2221"
current_service_port=""
current_target_ip=""
current_target_port=""

#####################################################################################################
# FUNÇÕES DE PERSISTÊNCIA
#####################################################################################################

save_config() {
    cat > "$CONFIG_FILE" << EOF
servidor1_full="$servidor1_full"
servidor2_full="$servidor2_full"
password_servidor2="$password_servidor2"
porta_local_tunel1="$porta_local_tunel1"
EOF
}

load_config() {
    if [[ -f "$CONFIG_FILE" ]]; then
        source "$CONFIG_FILE"
        return 0
    fi
    return 1
}

save_tunnel1_pid() {
    echo "$1" > "$TUNNEL1_PID_FILE"
}

save_tunnel2_pid() {
    echo "$1" > "$TUNNEL2_PID_FILE"
}

get_tunnel1_pid() {
    if [[ -f "$TUNNEL1_PID_FILE" ]]; then
        cat "$TUNNEL1_PID_FILE"
    else
        echo ""
    fi
}

get_tunnel2_pid() {
    if [[ -f "$TUNNEL2_PID_FILE" ]]; then
        cat "$TUNNEL2_PID_FILE"
    else
        echo ""
    fi
}

save_service_config() {
    local service_id="$1"
    cat > "$CONFIG_DIR/service_$service_id" << EOF
target_ip="$2"
target_port="$3"
local_port="$4"
EOF
}

load_service_config() {
    local service_id="$1"
    if [[ -f "$CONFIG_DIR/service_$service_id" ]]; then
        source "$CONFIG_DIR/service_$service_id"
        return 0
    fi
    return 1
}

#####################################################################################################
# FUNÇÕES DE INTERFACE
#####################################################################################################

print_header() {
    clear
    echo -e "${CYAN}╔════════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${CYAN}║        Sistema Gerenciador de Túneis SSH Independentes        ║${NC}"
    echo -e "${CYAN}╚════════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

print_status() {
    echo -e "${YELLOW}┌─────────────────────────────────────────────────────────────┐${NC}"
    echo -e "${YELLOW}│                     STATUS DOS TÚNEIS                      │${NC}"
    echo -e "${YELLOW}└─────────────────────────────────────────────────────────────┘${NC}"

    # Status do Túnel 1
    local tunnel1_pid=$(get_tunnel1_pid)
    if [[ -n "$tunnel1_pid" ]] && kill -0 "$tunnel1_pid" 2>/dev/null; then
        echo -e "  📡 Túnel 1 (Gateway): ${GREEN}● ATIVO${NC} [PID: $tunnel1_pid]"
        if [[ -n "$servidor1_full" ]]; then
            echo -e "     └─ $servidor1_full → Gateway SSH"
        fi
    else
        echo -e "  📡 Túnel 1 (Gateway): ${RED}○ INATIVO${NC}"
    fi

    # Status do Túnel 2
    local tunnel2_pid=$(get_tunnel2_pid)
    if [[ -n "$tunnel2_pid" ]] && kill -0 "$tunnel2_pid" 2>/dev/null; then
        echo -e "  🎯 Túnel 2 (Serviço): ${GREEN}● ATIVO${NC} [PID: $tunnel2_pid]"
        if [[ -n "$current_target_ip" ]]; then
            echo -e "     └─ localhost:$current_service_port → $current_target_ip:$current_target_port"
        fi
    else
        echo -e "  🎯 Túnel 2 (Serviço): ${RED}○ INATIVO${NC}"
    fi
    echo ""
}

show_main_menu() {
    print_header
    print_status

    echo -e "${BLUE}┌─────────────────────────────────────────────────────────────┐${NC}"
    echo -e "${BLUE}│                      MENU PRINCIPAL                        │${NC}"
    echo -e "${BLUE}└─────────────────────────────────────────────────────────────┘${NC}"
    echo ""
    echo -e "  ${CYAN}[1]${NC} 🔧 Configurar/Iniciar Túnel 1 (Gateway)"
    echo -e "  ${CYAN}[2]${NC} 🎯 Configurar/Iniciar Túnel 2 (Serviço)"
    echo -e "  ${CYAN}[3]${NC} 🔄 Trocar serviço do Túnel 2 (mantém Túnel 1)"
    echo -e "  ${CYAN}[4]${NC} 📊 Monitorar túneis ativos"
    echo -e "  ${CYAN}[5]${NC} 🛑 Parar Túnel 1"
    echo -e "  ${CYAN}[6]${NC} 🛑 Parar Túnel 2"
    echo -e "  ${CYAN}[7]${NC} 🔄 Reiniciar todos os túneis"
    echo -e "  ${CYAN}[8]${NC} 📋 Ver configurações salvas"
    echo -e "  ${CYAN}[9]${NC} 🗑️  Limpar todas as configurações"
    echo -e "  ${CYAN}[0]${NC} ❌ Sair"
    echo ""
    echo -e "${YELLOW}────────────────────────────────────────────────────────────${NC}"
    read -p "Escolha uma opção: " choice

    case $choice in
        1) setup_tunnel1 ;;
        2) setup_tunnel2 ;;
        3) switch_service ;;
        4) monitor_tunnels ;;
        5) stop_tunnel1 ;;
        6) stop_tunnel2 ;;
        7) restart_all ;;
        8) show_configs ;;
        9) clear_all ;;
        0) cleanup_and_exit ;;
        *) echo -e "${RED}Opção inválida!${NC}"; sleep 1 ;;
    esac
}

#####################################################################################################
# FUNÇÕES DO TÚNEL 1
#####################################################################################################

setup_tunnel1() {
    print_header
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${CYAN}              CONFIGURAÇÃO DO TÚNEL 1 (GATEWAY)              ${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""

    # Verificar se já está rodando
    local tunnel1_pid=$(get_tunnel1_pid)
    if [[ -n "$tunnel1_pid" ]] && kill -0 "$tunnel1_pid" 2>/dev/null; then
        echo -e "${YELLOW}⚠️  Túnel 1 já está ativo!${NC}"
        echo ""
        echo "  [1] Reconfigurar (irá parar o túnel atual)"
        echo "  [2] Voltar ao menu"
        read -p "Escolha: " choice
        if [[ "$choice" != "1" ]]; then
            return
        fi
        stop_tunnel1
    fi

    # Carregar configuração se existir
    if load_config && [[ -n "$servidor1_full" ]]; then
        echo -e "${GREEN}📂 Configuração anterior encontrada:${NC}"
        echo -e "   Servidor: $servidor1_full"
        echo -e "   Gateway: $servidor2_full"
        echo ""
        echo "  [1] Usar configuração existente"
        echo "  [2] Nova configuração"
        read -p "Escolha: " use_existing

        if [[ "$use_existing" == "1" ]]; then
            start_tunnel1
            return
        fi
    fi

    # Nova configuração
    echo -e "${YELLOW}Digite as informações do servidor Tailscale:${NC}"
    read -p "Usuario@Servidor: " servidor1_full

    if [[ ! "$servidor1_full" =~ ^[^@]+@[^@]+$ ]]; then
        echo -e "${RED}❌ Formato inválido! Use: usuario@servidor${NC}"
        sleep 2
        return
    fi

    echo ""
    echo -e "${YELLOW}Digite as informações do Gateway/pfSense:${NC}"
    read -p "Usuario@IP: " servidor2_full

    if [[ ! "$servidor2_full" =~ ^[^@]+@[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        echo -e "${RED}❌ Formato inválido! Use: usuario@IP${NC}"
        sleep 2
        return
    fi

    read -s -p "Senha do Gateway: " password_servidor2
    echo ""

    # Salvar e iniciar
    save_config
    start_tunnel1
}

start_tunnel1() {
    echo ""
    echo -e "${YELLOW}🚀 Iniciando Túnel 1...${NC}"

    local servidor2_ip=$(echo $servidor2_full | cut -d'@' -f2)

    ssh $scpoptions "$servidor1_full" -N -L "$porta_local_tunel1:$servidor2_ip:22" &
    local pid=$!

    sleep 3

    if kill -0 $pid 2>/dev/null; then
        save_tunnel1_pid $pid
        echo -e "${GREEN}✅ Túnel 1 estabelecido com sucesso! [PID: $pid]${NC}"
        echo -e "${CYAN}   Gateway SSH disponível em: localhost:$porta_local_tunel1${NC}"
    else
        echo -e "${RED}❌ Falha ao estabelecer Túnel 1${NC}"
        echo -e "${YELLOW}   Verifique as chaves SSH para $servidor1_full${NC}"
    fi

    echo ""
    read -p "Pressione Enter para continuar..."
}

stop_tunnel1() {
    local tunnel1_pid=$(get_tunnel1_pid)
    if [[ -n "$tunnel1_pid" ]] && kill -0 "$tunnel1_pid" 2>/dev/null; then
        kill "$tunnel1_pid"
        rm -f "$TUNNEL1_PID_FILE"
        echo -e "${GREEN}✅ Túnel 1 parado${NC}"

        # Parar Túnel 2 também se estiver ativo
        local tunnel2_pid=$(get_tunnel2_pid)
        if [[ -n "$tunnel2_pid" ]] && kill -0 "$tunnel2_pid" 2>/dev/null; then
            echo -e "${YELLOW}⚠️  Parando Túnel 2 (dependente do Túnel 1)...${NC}"
            stop_tunnel2
        fi
    else
        echo -e "${YELLOW}Túnel 1 não está ativo${NC}"
    fi
}

#####################################################################################################
# FUNÇÕES DO TÚNEL 2
#####################################################################################################

setup_tunnel2() {
    print_header
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${CYAN}              CONFIGURAÇÃO DO TÚNEL 2 (SERVIÇO)              ${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""

    # Verificar se Túnel 1 está ativo
    local tunnel1_pid=$(get_tunnel1_pid)
    if [[ -z "$tunnel1_pid" ]] || ! kill -0 "$tunnel1_pid" 2>/dev/null; then
        echo -e "${RED}❌ ERRO: Túnel 1 não está ativo!${NC}"
        echo -e "${YELLOW}   É necessário estabelecer o Túnel 1 primeiro.${NC}"
        echo ""
        read -p "Deseja configurar o Túnel 1 agora? (s/n): " setup_t1
        if [[ "$setup_t1" =~ ^[Ss]$ ]]; then
            setup_tunnel1
        fi
        return
    fi

    # Verificar se já está rodando
    local tunnel2_pid=$(get_tunnel2_pid)
    if [[ -n "$tunnel2_pid" ]] && kill -0 "$tunnel2_pid" 2>/dev/null; then
        echo -e "${YELLOW}⚠️  Túnel 2 já está ativo!${NC}"
        echo -e "   Conectado a: $current_target_ip:$current_target_port"
        echo ""
        echo "  [1] Parar e reconfigurar"
        echo "  [2] Voltar ao menu"
        read -p "Escolha: " choice
        if [[ "$choice" != "1" ]]; then
            return
        fi
        stop_tunnel2
    fi

    configure_service
}

configure_service() {
    echo ""
    echo -e "${YELLOW}Configure o serviço de destino:${NC}"
    read -p "IP do serviço: " target_ip

    if [[ ! "$target_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        echo -e "${RED}❌ IP inválido!${NC}"
        sleep 2
        return
    fi

    read -p "Porta do serviço: " target_port

    if [[ ! "$target_port" =~ ^[0-9]+$ ]] || [ "$target_port" -lt 1 ] || [ "$target_port" -gt 65535 ]; then
        echo -e "${RED}❌ Porta inválida!${NC}"
        sleep 2
        return
    fi

    # Calcular porta local
    local local_port=$((8000 + target_port))
    if [ $local_port -gt 65535 ]; then
        local_port=$((target_port + 1000))
        if [ $local_port -gt 65535 ]; then
            local_port=$((9000 + (target_port % 1000)))
        fi
    fi

    read -p "Porta local [$local_port]: " custom_port
    if [[ -n "$custom_port" ]]; then
        local_port=$custom_port
    fi

    # Salvar e iniciar
    current_target_ip="$target_ip"
    current_target_port="$target_port"
    current_service_port="$local_port"

    # Gerar ID único para o serviço
    local service_id=$(date +%s)
    save_service_config "$service_id" "$target_ip" "$target_port" "$local_port"

    start_tunnel2
}

start_tunnel2() {
    echo ""
    echo -e "${YELLOW}🚀 Iniciando Túnel 2...${NC}"

    if ! load_config; then
        echo -e "${RED}❌ Configuração do Gateway não encontrada!${NC}"
        return
    fi

    local servidor2_user=$(echo $servidor2_full | cut -d'@' -f1)

    sshpass -p "$password_servidor2" ssh $scpoptions "$servidor2_user@localhost" \
        -p "$porta_local_tunel1" \
        -N -L "$current_service_port:$current_target_ip:$current_target_port" &
    local pid=$!

    sleep 3

    if kill -0 $pid 2>/dev/null; then
        save_tunnel2_pid $pid
        echo -e "${GREEN}✅ Túnel 2 estabelecido com sucesso! [PID: $pid]${NC}"
        echo ""
        show_connection_info
    else
        echo -e "${RED}❌ Falha ao estabelecer Túnel 2${NC}"
        echo -e "${YELLOW}   Verifique as credenciais do Gateway${NC}"
    fi

    echo ""
    read -p "Pressione Enter para continuar..."
}

stop_tunnel2() {
    local tunnel2_pid=$(get_tunnel2_pid)
    if [[ -n "$tunnel2_pid" ]] && kill -0 "$tunnel2_pid" 2>/dev/null; then
        kill "$tunnel2_pid"
        rm -f "$TUNNEL2_PID_FILE"
        echo -e "${GREEN}✅ Túnel 2 parado${NC}"
    else
        echo -e "${YELLOW}Túnel 2 não está ativo${NC}"
    fi
}

switch_service() {
    print_header
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${CYAN}                    TROCAR SERVIÇO DO TÚNEL 2                ${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""

    # Verificar se Túnel 1 está ativo
    local tunnel1_pid=$(get_tunnel1_pid)
    if [[ -z "$tunnel1_pid" ]] || ! kill -0 "$tunnel1_pid" 2>/dev/null; then
        echo -e "${RED}❌ Túnel 1 não está ativo!${NC}"
        echo -e "${YELLOW}   É necessário que o Túnel 1 esteja ativo.${NC}"
        echo ""
        read -p "Pressione Enter para voltar..."
        return
    fi

    echo -e "${GREEN}✅ Túnel 1 está ativo - Gateway disponível${NC}"
    echo ""

    # Parar Túnel 2 se estiver ativo
    local tunnel2_pid=$(get_tunnel2_pid)
    if [[ -n "$tunnel2_pid" ]] && kill -0 "$tunnel2_pid" 2>/dev/null; then
        echo -e "${YELLOW}Parando Túnel 2 atual...${NC}"
        stop_tunnel2
        echo ""
    fi

    echo -e "${CYAN}Configure o novo serviço:${NC}"
    configure_service
}

#####################################################################################################
# FUNÇÕES DE MONITORAMENTO
#####################################################################################################

monitor_tunnels() {
    print_header
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${CYAN}                    MONITORAMENTO DOS TÚNEIS                 ${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    echo -e "${YELLOW}Pressione Ctrl+C para voltar ao menu${NC}"
    echo ""

    # Configurar trap local para esta função
    trap 'echo ""; echo -e "${CYAN}Voltando ao menu...${NC}"; sleep 1; return' SIGINT

    while true; do
        echo -e "\r\033[K${CYAN}[$(date '+%H:%M:%S')]${NC} Verificando status..."

        local tunnel1_pid=$(get_tunnel1_pid)
        local tunnel2_pid=$(get_tunnel2_pid)

        # Status Túnel 1
        if [[ -n "$tunnel1_pid" ]] && kill -0 "$tunnel1_pid" 2>/dev/null; then
            echo -e "\r\033[K${GREEN}● Túnel 1:${NC} Ativo [PID: $tunnel1_pid]"
        else
            echo -e "\r\033[K${RED}○ Túnel 1:${NC} Inativo"
        fi

        # Status Túnel 2
        if [[ -n "$tunnel2_pid" ]] && kill -0 "$tunnel2_pid" 2>/dev/null; then
            echo -e "${GREEN}● Túnel 2:${NC} Ativo [PID: $tunnel2_pid] → $current_target_ip:$current_target_port"
        else
            echo -e "${RED}○ Túnel 2:${NC} Inativo"
        fi

        sleep 5
        echo -e "\033[2A"  # Move cursor 2 linhas para cima
    done

    # Restaurar trap padrão ao sair
    trap - SIGINT
}

#####################################################################################################
# FUNÇÕES AUXILIARES
#####################################################################################################

show_connection_info() {
    echo -e "${MAGENTA}╔════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${MAGENTA}║                   INFORMAÇÕES DE CONEXÃO                  ║${NC}"
    echo -e "${MAGENTA}╚════════════════════════════════════════════════════════════╝${NC}"
    echo ""
    echo -e "  🎯 Serviço original: ${CYAN}$current_target_ip:$current_target_port${NC}"
    echo -e "  🔗 Acesso local: ${GREEN}localhost:$current_service_port${NC}"
    echo ""

    # Exemplos baseados na porta
    echo -e "${YELLOW}Exemplos de conexão:${NC}"
    case $current_target_port in
        22)   echo "  ssh usuario@localhost -p $current_service_port" ;;
        80)   echo "  curl http://localhost:$current_service_port" ;;
        443)  echo "  curl -k https://localhost:$current_service_port" ;;
        3389) echo "  RDP: localhost:$current_service_port" ;;
        3306) echo "  mysql -h localhost -P $current_service_port -u usuario -p" ;;
        5432) echo "  psql -h localhost -p $current_service_port -U usuario" ;;
        *)    echo "  Conectar em: localhost:$current_service_port" ;;
    esac
}

show_configs() {
    print_header
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${CYAN}                    CONFIGURAÇÕES SALVAS                     ${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""

    if load_config; then
        echo -e "${GREEN}Configuração do Gateway:${NC}"
        echo -e "  Servidor Tailscale: $servidor1_full"
        echo -e "  Gateway/pfSense: $servidor2_full"
        echo -e "  Porta local SSH: $porta_local_tunel1"
    else
        echo -e "${YELLOW}Nenhuma configuração de Gateway salva${NC}"
    fi

    echo ""

    # Listar serviços salvos
    local services=$(ls -1 "$CONFIG_DIR"/service_* 2>/dev/null)
    if [[ -n "$services" ]]; then
        echo -e "${GREEN}Serviços configurados:${NC}"
        for service_file in $services; do
            source "$service_file"
            local service_name=$(basename "$service_file")
            echo -e "  • $target_ip:$target_port → localhost:$local_port"
        done
    else
        echo -e "${YELLOW}Nenhum serviço configurado${NC}"
    fi

    echo ""
    read -p "Pressione Enter para continuar..."
}

restart_all() {
    echo -e "${YELLOW}Reiniciando todos os túneis...${NC}"

    # Parar tudo
    stop_tunnel2
    stop_tunnel1

    sleep 2

    # Reiniciar se houver configuração
    if load_config && [[ -n "$servidor1_full" ]]; then
        echo -e "${CYAN}Reiniciando Túnel 1...${NC}"
        start_tunnel1

        if [[ -n "$current_target_ip" ]]; then
            sleep 2
            echo -e "${CYAN}Reiniciando Túnel 2...${NC}"
            start_tunnel2
        fi
    else
        echo -e "${YELLOW}Nenhuma configuração salva para reiniciar${NC}"
    fi

    echo ""
    read -p "Pressione Enter para continuar..."
}

clear_all() {
    echo -e "${RED}⚠️  ATENÇÃO: Isso irá:${NC}"
    echo "  • Parar todos os túneis ativos"
    echo "  • Apagar todas as configurações salvas"
    echo ""
    read -p "Tem certeza? (s/n): " confirm

    if [[ "$confirm" =~ ^[Ss]$ ]]; then
        stop_tunnel2
        stop_tunnel1
        rm -rf "$CONFIG_DIR"
        mkdir -p "$CONFIG_DIR"
        echo -e "${GREEN}✅ Todas as configurações foram limpas${NC}"
    else
        echo -e "${YELLOW}Operação cancelada${NC}"
    fi

    sleep 2
}

cleanup_and_exit() {
    echo ""
    echo -e "${YELLOW}Encerrando...${NC}"

    echo "  [1] Manter túneis ativos em background"
    echo "  [2] Parar todos os túneis e sair"
    echo "  [3] Cancelar"
    read -p "Escolha: " exit_choice

    case $exit_choice in
        1)
            echo -e "${GREEN}✅ Túneis mantidos em background${NC}"
            echo -e "${CYAN}   Execute o script novamente para gerenciar${NC}"
            exit 0
            ;;
        2)
            stop_tunnel2
            stop_tunnel1
            echo -e "${GREEN}✅ Todos os túneis foram parados${NC}"
            exit 0
            ;;
        *)
            return
            ;;
    esac
}

#####################################################################################################
# MAIN
#####################################################################################################

# Verificar dependências
if ! command -v sshpass &> /dev/null; then
    echo -e "${RED}❌ ERRO: sshpass não está instalado!${NC}"
    echo -e "${YELLOW}   Ubuntu/Debian: sudo apt install sshpass${NC}"
    echo -e "${YELLOW}   CentOS/RHEL: sudo yum install sshpass${NC}"
    exit 1
fi

# Não usar trap global - deixar cada função gerenciar seu próprio trap

# Loop principal
while true; do
    show_main_menu
done
