#!/bin/bash
set -e

# === Configuration ===
SCRIPT_PATH="/usr/local/bin/set-tailscale-ip.sh"
SERVICE_PATH="/etc/systemd/system/tailscale-env.service"
ENV_FILE="/etc/tailscale.env"
PROFILE_BASH="/etc/profile.d/tailscale-env.sh"
PROFILE_ZSH="/etc/zsh/zshenv"
ZSH_MARKER="# >>> tailscale-env >>>"
ZSH_MARKER_END="# <<< tailscale-env <<<"
SERVICE_NAME="tailscale-env.service"

# === Couleurs ===
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log_ok()   { echo -e "${GREEN}✔${NC} $1"; }
log_skip() { echo -e "${YELLOW}⏭${NC} $1"; }
log_del()  { echo -e "${RED}✖${NC} $1"; }

# === Vérification root ===
check_root() {
    if [[ $EUID -ne 0 ]]; then
        echo "❌ Ce script doit être exécuté en root (sudo)"
        exit 1
    fi
}

# === Fonction INSTALL ===
install() {
    check_root

    # Vérification Tailscale installé
    if ! command -v tailscale &> /dev/null; then
        echo "❌ Tailscale n'est pas installé"
        exit 1
    fi

    echo ""
    echo "🔧 Installation de tailscale-env..."
    echo ""

    # 1. Création du script
    if [[ -f "$SCRIPT_PATH" ]]; then
        log_skip "Script $SCRIPT_PATH (déjà existant)"
    else
        cat > "$SCRIPT_PATH" << 'EOF'
#!/bin/bash
# Attend que Tailscale soit connecté (max 30s)
for i in {1..30}; do
    IP="$(/usr/bin/tailscale ip -4 2>/dev/null)"
    if [[ -n "$IP" ]]; then
        echo "TAILSCALE_IP=$IP" > /etc/tailscale.env
        exit 0
    fi
    sleep 1
done
echo "⚠ Tailscale IP non disponible après 30s" >&2
exit 1
EOF
        chmod +x "$SCRIPT_PATH"
        log_ok "Script créé : $SCRIPT_PATH"
    fi

    # 2. Création du service systemd
    if [[ -f "$SERVICE_PATH" ]]; then
        log_skip "Service $SERVICE_PATH (déjà existant)"
    else
        cat > "$SERVICE_PATH" << EOF
[Unit]
Description=Set Tailscale IP environment variable
After=tailscaled.service network-online.target
Wants=network-online.target
Requires=tailscaled.service

[Service]
Type=oneshot
ExecStart=$SCRIPT_PATH
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF
        log_ok "Service créé : $SERVICE_PATH"
    fi

    # 3. Création du script profile.d (pour bash)
    if [[ -f "$PROFILE_BASH" ]]; then
        log_skip "Profile bash $PROFILE_BASH (déjà existant)"
    else
        cat > "$PROFILE_BASH" << 'EOF'
# Charge les variables Tailscale si disponibles
if [[ -f /etc/tailscale.env ]]; then
    set -a
    source /etc/tailscale.env
    set +a
fi
EOF
        chmod +644 "$PROFILE_BASH"
        log_ok "Profile bash créé : $PROFILE_BASH"
    fi

    # 4. Configuration zsh (si zsh est installé)
    if command -v zsh &> /dev/null; then
        # Crée /etc/zsh si nécessaire
        [[ -d /etc/zsh ]] || mkdir -p /etc/zsh
        
        if [[ -f "$PROFILE_ZSH" ]] && grep -q "$ZSH_MARKER" "$PROFILE_ZSH" 2>/dev/null; then
            log_skip "Profile zsh $PROFILE_ZSH (déjà configuré)"
        else
            cat >> "$PROFILE_ZSH" << 'EOF'

# >>> tailscale-env >>>
# Charge les variables Tailscale si disponibles
if [[ -f /etc/tailscale.env ]]; then
    source /etc/tailscale.env
    export TAILSCALE_IP
fi
# <<< tailscale-env <<<
EOF
            log_ok "Profile zsh configuré : $PROFILE_ZSH"
        fi
    else
        log_skip "Zsh non installé, configuration zsh ignorée"
    fi

    # 5. Activation et démarrage du service
    systemctl daemon-reload
    if systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null; then
        log_skip "Service déjà activé"
    else
        systemctl enable "$SERVICE_NAME"
        log_ok "Service activé"
    fi

    echo ""
    echo "🚀 Exécution du service maintenant..."
    systemctl start "$SERVICE_NAME"

    # Vérification
    if [[ -f "$ENV_FILE" ]]; then
        source "$ENV_FILE"
        log_ok "IP Tailscale récupérée : $TAILSCALE_IP"
    else
        echo "⚠ Fichier $ENV_FILE non créé"
    fi

    # Message final
    echo ""
    echo "═══════════════════════════════════════════"
    echo " ✅ Installation terminée"
    echo "═══════════════════════════════════════════"
    echo ""
    echo " 📁 Script       : $SCRIPT_PATH"
    echo " 📁 Service      : $SERVICE_PATH"
    echo " 📁 Env file     : $ENV_FILE"
    echo " 📁 Profile bash : $PROFILE_BASH"
    if command -v zsh &> /dev/null; then
        echo " 📁 Profile zsh  : $PROFILE_ZSH"
    fi
    echo ""
    echo " 💡 Utilisation :"
    echo "    - Dans un service systemd :"
    echo "      EnvironmentFile=$ENV_FILE"
    echo ""
    echo "    - Dans un shell (après reconnexion) :"
    echo "      echo \$TAILSCALE_IP"
    echo ""
    echo " 🗑️  Désinstaller :"
    echo "      sudo $0 --uninstall"
    echo ""
    echo " ⚠️  Note : Reconnecte-toi (exit + ssh) pour avoir \$TAILSCALE_IP"
    echo ""
}

# === Fonction UNINSTALL ===
uninstall() {
    check_root

    echo ""
    echo "🗑️  Désinstallation de tailscale-env..."
    echo ""

    # Arrêt et désactivation du service
    if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
        systemctl stop "$SERVICE_NAME"
        log_del "Service arrêté"
    fi

    if systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null; then
        systemctl disable "$SERVICE_NAME"
        log_del "Service désactivé"
    fi

    # Suppression des fichiers
    for f in "$SCRIPT_PATH" "$SERVICE_PATH" "$ENV_FILE" "$PROFILE_BASH"; do
        if [[ -f "$f" ]]; then
            rm -f "$f"
            log_del "Supprimé : $f"
        fi
    done

    # Nettoyage de zshenv (suppression du bloc entre marqueurs)
    if [[ -f "$PROFILE_ZSH" ]] && grep -q "$ZSH_MARKER" "$PROFILE_ZSH" 2>/dev/null; then
        sed -i "/$ZSH_MARKER/,/$ZSH_MARKER_END/d" "$PROFILE_ZSH"
        log_del "Configuration zsh nettoyée : $PROFILE_ZSH"
    fi

    systemctl daemon-reload

    echo ""
    echo "═══════════════════════════════════════════"
    echo " ✅ Désinstallation terminée"
    echo "═══════════════════════════════════════════"
    echo ""
}

# === Fonction STATUS ===
show_status() {
    echo ""
    echo "📊 Statut de tailscale-env"
    echo "═══════════════════════════════════════════"
    echo ""

    # Script
    if [[ -f "$SCRIPT_PATH" ]]; then
        log_ok "Script présent : $SCRIPT_PATH"
    else
        log_del "Script absent : $SCRIPT_PATH"
    fi

    # Service file
    if [[ -f "$SERVICE_PATH" ]]; then
        log_ok "Service présent : $SERVICE_PATH"
    else
        log_del "Service absent : $SERVICE_PATH"
    fi

    # Profile bash
    if [[ -f "$PROFILE_BASH" ]]; then
        log_ok "Profile bash présent : $PROFILE_BASH"
    else
        log_del "Profile bash absent : $PROFILE_BASH"
    fi

    # Profile zsh
    if [[ -f "$PROFILE_ZSH" ]] && grep -q "$ZSH_MARKER" "$PROFILE_ZSH" 2>/dev/null; then
        log_ok "Profile zsh configuré : $PROFILE_ZSH"
    else
        log_del "Profile zsh non configuré"
    fi

    # Service enabled
    if systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null; then
        log_ok "Service activé au démarrage"
    else
        log_del "Service non activé au démarrage"
    fi

    # Service running
    if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
        log_ok "Service exécuté"
    else
        log_del "Service non exécuté"
    fi

    # Env file
    if [[ -f "$ENV_FILE" ]]; then
        source "$ENV_FILE"
        log_ok "Fichier env présent : $ENV_FILE"
        echo "    └─ TAILSCALE_IP=$TAILSCALE_IP"
    else
        log_del "Fichier env absent : $ENV_FILE"
    fi

    # Variable dans le shell actuel
    echo ""
    if [[ -n "${TAILSCALE_IP:-}" ]]; then
        log_ok "Variable \$TAILSCALE_IP disponible : $TAILSCALE_IP"
    else
        log_del "Variable \$TAILSCALE_IP non disponible (reconnecte-toi)"
    fi

    echo ""
}

# === Fonction HELP ===
show_help() {
    echo ""
    echo "Usage: $0 [OPTION]"
    echo ""
    echo "Options:"
    echo "  (sans option)    Installer tailscale-env"
    echo "  --uninstall, -u  Désinstaller tailscale-env"
    echo "  --status, -s     Afficher le statut"
    echo "  --help, -h       Afficher cette aide"
    echo ""
}

# === Main ===
case "${1:-}" in
    --uninstall|-u)
        uninstall
        ;;
    --status|-s)
        show_status
        ;;
    --help|-h)
        show_help
        ;;
    "")
        install
        ;;
    *)
        echo "❌ Option inconnue : $1"
        show_help
        exit 1
        ;;
esac
