#!/usr/bin/env bash
# ssl-localhost-ubuntu.sh
# Adaptado de ssl-localhost.sh para Ubuntu 24 + Let's Encrypt

# ——————————————————————
# Variables globales
# ——————————————————————
APACHE_PATH="/etc/apache2"
SSL_LIVE_DIR="/etc/letsencrypt/live"
VHOSTS_DIR="$APACHE_PATH/sites-available"
ORANGE='\033[38;5;208m'
RESET='\033[0m'

# Spinner
spin_chars=('|' '/' '-' '\\')
start_spinner() {
  spin_index=0
  (
    while :; do
      printf "\b${spin_chars[spin_index]}"
      spin_index=$(( (spin_index+1) % ${#spin_chars[@]} ))
      sleep 0.1
    done
  ) &
  spinner_pid=$!
  disown "$spinner_pid"
}
stop_spinner() {
  if [[ -n "${spinner_pid:-}" ]] && ps -p "$spinner_pid" > /dev/null 2>&1; then
    kill "$spinner_pid" >/dev/null 2>&1
    wait "$spinner_pid" 2>/dev/null
    printf "\b"
    unset spinner_pid
  fi
}

# ——————————————————————
# Helper para ejecutar comandos con spinner y capturar errores
# ——————————————————————
run_and_check() {
  local desc="$1"; shift
  printf "==> %s " "$desc"; start_spinner
  local output rc
  output=$("$@" 2>&1); rc=$?
  stop_spinner
  if [ $rc -ne 0 ]; then
    printf "\n......................................................................\n"
    printf "\n❌ Error en '%s':\n%s\n" "$desc" "$output"
    error_exit "$desc falló (código $rc)" \
               "Revisa logs: sudo journalctl -u apache2"
  else
    printf "... completado ✅\n"
    # Si hay alguna salida (warnings, notas, etc.) aun con rc=0, mostrarla
#    if [ -n "$output" ]; then
#      printf "⚠️ Mensaje de %s:\n%s\n" "$desc" "$output"
#    fi
  fi
}

# ——————————————————————
# Helper “verboso”: captura y muestra TODO el output
# ——————————————————————
verbose_check() {
  local desc="$1"; shift

  # Desactivar temporalmente 'errexit' para poder capturar rc y output
  set +e
  local output rc
  output=$("$@" 2>&1)
  rc=$?
  # Volver a activar 'errexit'
  set -e

  if [ $rc -ne 0 ]; then
    printf "==> %s ... ⚠️\n" "$desc"
    printf " \n......................................................................\n"
    printf "❌ Mensaje de '%s' (código %d):\n%s\n" "$desc" "$rc" "$output"
    error_exit "'$desc' falló (código $rc)" \
               "Revisa configuración y logs: sudo journalctl -u apache2"
  else
    # Mostramos siempre la salida, aunque rc==0
    #printf "✔ %s completado (código 0). Salida:\n%s\n" "$desc" "$output"
    printf "==> %s ... completado ✅\n" "$desc"
  fi
}

# Función central de errores
error_exit() {
  local message="$1"
  local suggestion="${2:-}"

  printf "\n❌ Error: %s\n" "$message"

  if [ -n "$suggestion" ]; then
    printf "➡️  %s" "$suggestion"
  fi

  printf "\n🔎 Revisa logs con: sudo journalctl -xe\n"
  printf "🔄 Puedes intentar depurar con: sudo apachectl -t\n"
  printf "......................................................................\n\n"
  printf "⏩ Saliendo de la aplicación ... \n\n"
  cleanup
  exit 1
}

confirm() {
  local prompt="$1" answer
  while true; do
    read -r -p "$prompt [s/n]: " answer
    case "$answer" in
      [sS]) return 0 ;;
      [nN]) return 1 ;;
      *) printf "Por favor ingresa 's' o 'n'.\n" ;;
    esac
  done
}

# ——————————————————————
# Modo dry-run (Certbot)
# ——————————————————————
DRYRUN=false
for arg in "$@"; do
  if [ "$arg" == "--dry-run" ]; then
    DRYRUN=true
  fi
done

# ——————————————————————
# 0. Solicitar y validar contraseña SUDO
# ——————————————————————
clear
printf "%b" "${ORANGE}"; figlet -f ogre pixellar; printf "%b" "${RESET}"
printf ">>>>>>>>>>>>>>>>>>> SSL :: MENU |\n\n"

attempts=3
while (( attempts > 0 )); do
  printf "Password: "
  stty -echo
  read PASS
  stty echo
  printf "\n🔑 Validando clave...\n"
  if echo "$PASS" | sudo -S -v >/dev/null 2>&1; then
    echo "✔ Clave correcta.\n"
    break
  else
    (( attempts-- ))
    echo "❌ Clave incorrecta. Intentos restantes: $attempts"
  fi
done

if (( attempts == 0 )); then
  printf "\n......................................................................\n"
  error_exit "🚫 Excediste el número de intentos de autenticación sudo." \
             "Verifica tu clave de usuario y vuelve a intentar."
fi

# ——————————————————————
# Mantener sudo activo en background
# ——————————————————————
(
  while true; do
    sleep 60
    echo "$PASS" | sudo -S -v >/dev/null 2>&1
  done
) &
SUDO_KEEPALIVE_PID=$!
disown "$SUDO_KEEPALIVE_PID"

# ——————————————————————
# Función de limpieza
# ——————————————————————
cleanup() {
  stop_spinner 2>/dev/null || true
  kill "$SUDO_KEEPALIVE_PID" >/dev/null 2>&1
  sudo -k
}

# ——————————————————————
# Manejo de señales abruptas
# ——————————————————————
handle_exit() {
  printf "\n⏩ Saliendo de la aplicación ... \n\n"
  cleanup
  exit 1
}

trap 'handle_exit' INT TSTP
trap 'cleanup' EXIT

# ——————————————————————
# 1. Verificar e instalar dependencias
# ——————————————————————
install_ssl() {
  set -euo pipefail

  OS_INFO="$(lsb_release -d | cut -f2)"
  clear
  printf "%b" "${ORANGE}"; figlet -f ogre pixellar; printf "%b" "${RESET}"
  printf ">>>>>>>>>>>>>>>> SSL :: INSTALL |\n\n"
  echo "---------------------------------"
  printf "OS:     %s\n" "$OS_INFO"
  printf "APACHE: %s\n" "$APACHE_PATH"
  echo "---------------------------------"
  echo

  ### 1) Verificar e instalar dependencias ###
  checks=("apache2" "certbot" "python3-certbot-apache")
  total=${#checks[@]}
  completed=0
  need_install=()
  printf "Verificando dependencias… 0%% completado"
  for tool in "${checks[@]}"; do
    dpkg -s "$tool" &>/dev/null || need_install+=("$tool")
    completed=$((completed + 1))
    printf "\rVerificando dependencias… %d%% completado" $(( completed * 100 / total ))
  done
  printf "\n"
  if command -v tput >/dev/null && [ -t 1 ]; then
    tput cuu1 && tput el
  else
    printf "\033[A\033[2K"
  fi

  if [ ${#need_install[@]} -gt 0 ]; then
    printf "Faltan las siguientes dependencias: %s\n" "${need_install[*]}"
    if confirm "¿Instalar ahora?"; then
      printf "==> Instalando dependencias "; start_spinner
      sudo apt update >/dev/null 2>&1
      sudo apt install -y "${need_install[@]}" >/dev/null 2>&1
      stop_spinner; printf "... completado ✅\n"
    else
      error_exit "Faltan dependencias: ${need_install[*]}" \
                 "Ejecuta manualmente 'sudo apt install ${need_install[*]}' y vuelve a intentar."
    fi
  fi

  ### 2) Pedir dominio y rutas ###
  while true; do
    read -r -p "Dominio local a usar (ej: pixellar.local): " DOMAIN
    if [[ -z "$DOMAIN" ]]; then
      printf "❌ Debes ingresar un dominio.\n"; continue
    fi
    if [[ "$DOMAIN" =~ ^https?:// ]]; then
      printf "❌ No incluyas 'http://' ni 'https://'.\n"; continue
    fi
    if ! [[ "$DOMAIN" =~ ^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])$ && "$DOMAIN" = *.* ]]; then
      printf "❌ Formato no válido. Ej: pixellar.local\n"; continue
    fi
    break
  done

  # Microservicios o DocumentRoot
  while true; do
    read -r -p "¿El dominio será manejado con microservicios? (s/n): " svc_answer
    case "$svc_answer" in
      [sS]) USE_MICROSERVICES=true; break ;;
      [nN]) USE_MICROSERVICES=false; break ;;
      *) echo "Por favor ingresa 's' o 'n'." ;;
    esac
  done

  if $USE_MICROSERVICES; then
    while true; do
      read -r -p "Puerto ROOT (ej: 1013): " PORTROOT
      [[ "$PORTROOT" =~ ^[0-9]+$ ]] && break || printf "❌ Puerto no válido.\n"
    done
  else
    read -r -p "DocumentRoot (ruta absoluta): " DOCUMENTROOT
  fi

  # Resumen
  if $USE_MICROSERVICES; then
    printf "\nDominio:     %s\nPuerto ROOT: %s\n\n" "$DOMAIN" "$PORTROOT"
  else
    printf "\nDominio:       %s\nDocumentRoot:  %s\n\n" "$DOMAIN" "$DOCUMENTROOT"
  fi

  ### 3) Crear VHOST HTTP ###
  VHOST_FILE="$VHOSTS_DIR/$DOMAIN.conf"
  printf "==> Creando VirtualHost HTTP en '%s' " "$VHOST_FILE"
  start_spinner
  sudo mkdir -p "$VHOSTS_DIR"
  sudo bash -c "cat > '$VHOST_FILE'" <<EOF
<VirtualHost *:80>
  ServerName $DOMAIN
  RewriteEngine On
  RewriteRule ^/(.*)\$ https://$DOMAIN/\$1 [R=301,L]
</VirtualHost>
EOF
  stop_spinner; printf "... completado ✅\n"

  ### 4) Añadir dominio a /etc/hosts ###
  if ! grep -qE "^127\.0\.0\.1.*\b${DOMAIN}\b" /etc/hosts; then
    sudo sed -E -i "/^127\.0\.0\.1[[:space:]]/ s/\$/ ${DOMAIN}/" /etc/hosts
    sudo sed -E -i 's/[[:space:]]{2,}/ /g' /etc/hosts
    printf "==> Añadido '%s' a línea IPv4 ✅\n" "$DOMAIN"
  else
    printf "==> IPv4 '%s' ya presente ✅\n" "$DOMAIN"
  fi

  if ! grep -qE "^::1.*\b${DOMAIN}\b" /etc/hosts; then
    sudo sed -E -i "/^::1[[:space:]]/ s/\$/ ${DOMAIN}/" /etc/hosts
    sudo sed -E -i 's/[[:space:]]{2,}/ /g' /etc/hosts
    printf "==> Añadido '%s' a línea IPv6 ✅\n" "$DOMAIN"
  else
    printf "==> IPv6 '%s' ya presente ✅\n" "$DOMAIN"
  fi

  ### 5) Activar sitio HTTP ###
  printf "==> Activando sitio '%s' " "$DOMAIN.conf"
  start_spinner
  sudo a2ensite "$DOMAIN.conf" >/dev/null 2>&1
  stop_spinner; printf "... completado ✅\n"

  ### 6) Reiniciar Apache para validar HTTP ###
  verbose_check "Validando APACHE" sudo apachectl configtest
  printf "==> Verificando estado de Apache antes de reiniciar...\n"
  if systemctl is-active --quiet apache2; then
    verbose_check "Reiniciando APACHE" sudo systemctl reload apache2
  else
    printf "⚠️  Apache no está activo. Se intentará iniciar.\n"
    verbose_check "Iniciando APACHE" sudo systemctl start apache2
  fi

  ### 7) Obtener Certificado Let's Encrypt ###
  FIXED_TEXT="==> Solicitando certificado TLS de Let's Encrypt para "
  dashline_length=$(( ${#FIXED_TEXT} + ${#DOMAIN} ))
  dashline=$(printf '%*s' "$dashline_length" '' | tr ' ' '*')

  # 1. Verificar resolución DNS local
  if ! getent hosts "$DOMAIN" > /dev/null; then
    error_exit "El dominio '$DOMAIN' no resuelve en DNS o /etc/hosts." \
               "Verifica que esté en /etc/hosts o configurado en DNS local."
  fi

  # 2. Verificar respuesta HTTP o redirección antes de certbot
  http_code=$(curl -s -o /dev/null -w "%{http_code}" "http://$DOMAIN")
  if ! [[ $http_code =~ ^(200|301)$ ]]; then
    error_exit "Se obtuvo código HTTP $http_code de 'http://$DOMAIN'." \
               "Verifica tu VirtualHost en puerto 80 y la accesibilidad."
  fi

  # 3. Solicitar Certificado TLS (dry-run o real)
  if $DRYRUN; then
    printf "==> Ejecutando Certbot en modo --dry-run para '%s'\n\n" "$DOMAIN"
    echo "$dashline"
    if ! sudo certbot certonly --apache -d "$DOMAIN" --dry-run; then
      error_exit "Fallo en el dry-run de certbot para '$DOMAIN'." \
                 "Revisa si el dominio apunta a esta máquina y Apache responde."
    fi
  else
    printf "==> Solicitando certificado TLS de Let's Encrypt para '%s'\n\n" "$DOMAIN"
    echo "$dashline"
    if ! sudo certbot certonly --apache -d "$DOMAIN" --no-redirect; then
      printf " \n......................................................................"
      error_exit "Fallo al obtener certificado TLS con certbot para '$DOMAIN'." \
                 "Revisa que el dominio apunte correctamente y no existan errores en Apache."
    fi
  fi

  # 4. Verificar existencia del certificado generado
  CERT_PATH="$SSL_LIVE_DIR/$DOMAIN"
  if [ ! -d "$CERT_PATH" ]; then
    error_exit "No se encontró certificado en '$CERT_PATH' tras ejecutar certbot." \
               "Verifica permisos, logs de certbot y acceso a la carpeta."
  fi

  ### 8) Crear VirtualHost HTTPS 443 ###
  echo "$dashline"
  printf "\n==> Configurando VirtualHost HTTPS en '%s' " "$VHOST_FILE"
  start_spinner
  if $USE_MICROSERVICES; then
    sudo bash -c "cat >> '$VHOST_FILE'" <<EOF
<VirtualHost *:443>
  ServerName $DOMAIN

  SSLEngine on
  SSLCertificateFile    ${CERT_PATH}/fullchain.pem
  SSLCertificateKeyFile ${CERT_PATH}/privkey.pem

  ProxyPreserveHost On
  ProxyPass        "/"  "http://127.0.0.1:${PORTROOT}/" retry=0
  ProxyPassReverse "/"  "http://127.0.0.1:${PORTROOT}/"

  Header always set X-Frame-Options        "SAMEORIGIN"
  Header always set X-Content-Type-Options "nosniff"

  ErrorLog  \${APACHE_LOG_DIR}/${DOMAIN}-error.log
  CustomLog \${APACHE_LOG_DIR}/${DOMAIN}-access.log combined
</VirtualHost>
EOF
  else
    sudo bash -c "cat >> '$VHOST_FILE'" <<EOF
<VirtualHost *:443>
  ServerName $DOMAIN

  SSLEngine on
  SSLCertificateFile    ${CERT_PATH}/fullchain.pem
  SSLCertificateKeyFile ${CERT_PATH}/privkey.pem

  DocumentRoot "$DOCUMENTROOT"
  <Directory "$DOCUMENTROOT">
    Require all granted
  </Directory>

  ErrorLog  \${APACHE_LOG_DIR}/${DOMAIN}-error.log
  CustomLog \${APACHE_LOG_DIR}/${DOMAIN}-access.log combined
</VirtualHost>
EOF
  fi
  stop_spinner; printf "... completado ✅\n"

  ### 9) Validar y reiniciar Apache final ###
  verbose_check "Validando APACHE" sudo apachectl configtest
  printf "==> Verificando estado de Apache antes de reiniciar...\n"
  if systemctl is-active --quiet apache2; then
    verbose_check "Reiniciando APACHE" sudo systemctl reload apache2
  else
    printf "⚠️  Apache no está activo. Se intentará iniciar.\n"
    verbose_check "Iniciando APACHE" sudo systemctl start apache2
  fi

  dashline=$(printf '%*s' "$dashline_length" '' | tr ' ' '=')
  echo
  echo "$dashline"
  printf " ¡Listo! Prueba: https://%s\n" "$DOMAIN"
  echo "$dashline"

  printf "\n[ENTER para continuar]"
  while IFS= read -rsn1 key; do [[ $key == "" ]] && break; done
}

# ——————————————————————
# Listar SSL activos
# ——————————————————————
list_ssl() {
  clear
  printf "%b" "${ORANGE}"; figlet -f ogre pixellar; printf "%b" "${RESET}"
  printf ">>>>>>>>>>>>>>>>>>> SSL :: LIST |\n\n"

  echo "-----------------------"
  printf "Dominios con SSL activo\n"
  echo "-----------------------"

  if [ -d "$SSL_LIVE_DIR" ]; then
    found=false
    for dir in "$SSL_LIVE_DIR"/*; do
      [ -d "$dir" ] || continue
      domain=$(basename "$dir")
      printf "%s\n" "📌 $domain"
      found=true
    done
    $found || printf "(No se encontraron carpetas en %s)\n" "$SSL_LIVE_DIR"
  else
    printf "El directorio %s no existe.\n" "$SSL_LIVE_DIR"
  fi

  printf "\n[ENTER para continuar]"
  while true; do
    IFS= read -rsn1 key
    case "$key" in
      "") break ;;
      $'\x1b') ;;
      $'\t') ;;
      ' ') ;;
      *) ;;
    esac
  done
}

# ——————————————————————
# Borrar SSL + VHOST
# ——————————————————————
delete_ssl() {
  local domains=() select_state=() cursor=0 key selected_indices=() answer domain_escaped

  # Cabecera
  clear
  printf "%b" "${ORANGE}"; figlet -f ogre pixellar; printf "%b" "${RESET}"
  printf ">>>>>>>>>>>>>>>>>>> SSL :: BORRAR |\n\n"

  # Listar dominios con SSL
  if [ -d "$SSL_LIVE_DIR" ]; then
    for d in "$SSL_LIVE_DIR"/*; do
      [ -d "$d" ] || continue
      domains+=("$(basename "$d")")
    done
  fi

  if [ ${#domains[@]} -eq 0 ]; then
    printf "\nNo hay dominios para borrar.\n\n[ENTER para continuar]"
    IFS= read -rsn1 _
    return
  fi

  # Inicializar selección
  for ((i=0; i<${#domains[@]}; i++)); do
    select_state[i]=0
  done

  # Menú de selección
  while true; do
    cursor=0
    while true; do
      clear
      printf "%b" "${ORANGE}"; figlet -f ogre pixellar; printf "%b" "${RESET}"
      printf ">>>>>>>>>>>>>>>>>>> SSL :: BORRAR |\n\n"
      echo "------------------------------------------------------"
      printf "↑ ↓, SPACE: Seleccionar, ENTER: Confirmar, ←: Regresar\n"
      echo "------------------------------------------------------"

      for i in "${!domains[@]}"; do
        [ "$i" -eq "$cursor" ] && color="\033[32m" || color="\033[0m"
        [ "${select_state[i]}" -eq 1 ] && marker="[x]" || marker="[ ]"
        printf "${color}%s %s\033[0m\n" "$marker" "${domains[i]}"
      done

      IFS= read -rsn1 key
      if [[ $key == $'\x1b' ]]; then
        read -rsn2 key
        [[ $key == "[A" ]] && ((cursor=(cursor-1+${#domains[@]})%${#domains[@]}))
        [[ $key == "[B" ]] && ((cursor=(cursor+1)%${#domains[@]}))
        [[ $key == "[D" ]] && { return; }
      elif [[ $key == " " ]]; then
        select_state[cursor]=$((1-select_state[cursor]))
      elif [[ -z "$key" ]]; then
        if printf '%s\n' "${select_state[@]}" | grep -q 1; then break; fi
      fi
    done

    # Confirmar selección
    selected_indices=()
    for idx in "${!select_state[@]}"; do
      [ "${select_state[idx]}" -eq 1 ] && selected_indices+=("${domains[idx]}")
    done

    printf "\n¿Está seguro que desea borrar estos dominios? [s/n]: "
    read -r answer
    [[ "$answer" =~ ^[sS]$ ]] && break
  done

  # Proceso de borrado robusto
  for domain in "${selected_indices[@]}"; do
    printf "\n➡️  Procesando dominio: %s\n" "$domain"

    # 1. Borrar certificado Let's Encrypt
    if [ -d "$SSL_LIVE_DIR/$domain" ]; then
      printf "\n***********************************************************************\n\n"
      if sudo certbot delete --cert-name "$domain"; then
        printf "\n***********************************************************************\n\n"
        printf "✅ Certificado Let's Encrypt de '%s' eliminado.\n" "$domain"
      else
        printf "❌ Error al intentar borrar certificado de '%s'.\n" "$domain"
      fi
    else
      printf "⚠️ No existe certificado en %s (ya eliminado).\n" "$SSL_LIVE_DIR/$domain"
    fi

    # 2. Borrar VHOST
    if [ -f "$VHOSTS_DIR/$domain.conf" ]; then
      if sudo rm -f "$VHOSTS_DIR/$domain.conf"; then
        printf "✅ VirtualHost '%s.conf' eliminado.\n" "$domain"
      else
        printf "❌ Error al intentar borrar VirtualHost '%s.conf'.\n" "$domain"
      fi
    else
      printf "⚠️ No existe VirtualHost en '%s'.\n" "$VHOSTS_DIR/$domain.conf"
    fi

    # 3. Limpiar /etc/hosts (IPv4 & IPv6)
    domain_escaped=${domain//./\\.}
    for ip in "127.0.0.1" "::1"; do
      if grep -qE "^$ip[[:space:]].*\b${domain}\b" /etc/hosts; then
        sudo sed -i -E "/^$ip[[:space:]]/ s/([[:space:]])${domain_escaped}([[:space:]]|$)/\1\2/g" /etc/hosts
        sudo sed -i -E "/^$ip[[:space:]]/ s/[[:space:]]{2,}/ /g" /etc/hosts
        printf "✅ Dominio '%s' eliminado de línea %s en /etc/hosts.\n" "$domain" "$ip"
      else
        printf "⚠️  Dominio '%s' no encontrado en línea %s de /etc/hosts.\n" "$domain" "$ip"
      fi
    done
  done

  # Validar y reiniciar Apache
  verbose_check "Validando configuración de Apache" sudo apachectl configtest
  printf "==> Verificando estado de Apache...\n"
  if systemctl is-active --quiet apache2; then
    verbose_check "Reiniciando Apache" sudo systemctl reload apache2
  else
    printf "⚠️  Apache no está activo. Se intentará iniciar.\n"
    verbose_check "Iniciando Apache" sudo systemctl start apache2
  fi

  printf "\n[ENTER para continuar]"
  while IFS= read -rsn1 key; do [[ $key == "" ]] && break; done
}

# ——————————————————————
# Función para salir
# ——————————————————————
exit_ssl() {
  printf "\n⏩ Saliendo de la aplicacion ... \n\n"
  cleanup
  exit 0
}

# ——————————————————————
# Menú principal
# ——————————————————————
options=("📚 Listar" "🔑 Instalar" "⛔ Borrar" "🚪 Salir")
num_options=${#options[@]}
print_menu() {
  clear
  printf "%b" "${ORANGE}"; figlet -f ogre pixellar; printf "%b" "${RESET}"
  printf ">>>>>>>>>>>>>>>>>>> SSL :: MENU |\n\n"
  echo "---------------------"
  printf "↑ ↓, ENTER: Confirmar\n"
  echo "---------------------"
  for i in "${!options[@]}"; do
    color=$([[ $i -eq $cursor ]] && echo "\033[32m" || echo "\033[0m")
    printf "${color}%s\033[0m\n" "${options[i]}"
  done
}

clear
printf "%b" "${ORANGE}"; figlet -f ogre pixellar; printf "%b" "${RESET}"
printf ">>>>>>>>>>>>>>>>>>> SSL :: MENU |\n\n"

while true; do
  cursor=0
  while true; do
    print_menu
    IFS= read -rsn1 key
    if [[ $key == $'\x1b' ]]; then
      read -rsn2 rest; key+="$rest"
      [[ $key == $'\x1b[A' ]] && ((cursor=(cursor-1+num_options)%num_options))
      [[ $key == $'\x1b[B' ]] && ((cursor=(cursor+1)%num_options))
    elif [[ -z "$key" ]]; then
      break
    fi
  done
  case "${options[cursor]}" in
    "📚 Listar")   list_ssl ;;
    "🔑 Instalar") install_ssl ;;
    "⛔ Borrar")   delete_ssl ;;
    "🚪 Salir")   exit_ssl ;;
  esac
done