#!/bin/bash

SYSTEMD_DIR=/etc/systemd/system
SERVICE_FILE=$SYSTEMD_DIR/ehc602.service

# Contenuto atteso del service file
EXPECTED_CONTENT=$(cat <<'EOF'
[Unit]
Description=EHC602 service
# Aspetta che i device siano pronti
After=systemd-udev-settle.service
Wants=systemd-udev-settle.service

[Service]
WorkingDirectory=/home/pi/ehc602/backend
ExecStartPre=/usr/bin/sleep 2
ExecStart=/home/pi/ehc602/backend/start-ehc.sh
Restart=on-failure
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target
EOF
)

# --- Installa / aggiorna ehc602.service ---

INSTALL_SERVICE=false

if [ ! -f "$SERVICE_FILE" ]; then
    echo "File $SERVICE_FILE non trovato. Installazione in corso..."
    INSTALL_SERVICE=true
else
    CURRENT_CONTENT=$(cat "$SERVICE_FILE")
    if [ "$CURRENT_CONTENT" != "$EXPECTED_CONTENT" ]; then
        echo "File $SERVICE_FILE non aggiornato. Aggiornamento in corso..."
        INSTALL_SERVICE=true
    else
        echo "File $SERVICE_FILE già aggiornato. Nessuna azione necessaria."
    fi
fi

if [ "$INSTALL_SERVICE" = true ]; then
    echo "$EXPECTED_CONTENT" > "$SERVICE_FILE"
    # Crea il symlink manualmente (equivalente a systemctl enable) senza daemon-reload,
    # che disturberebbe il servizio init.d attualmente in esecuzione.
    # Il riavvio successivo caricherà il nuovo service file.
    WANTS_DIR=/etc/systemd/system/multi-user.target.wants
    mkdir -p "$WANTS_DIR"
    ln -sf "$SERVICE_FILE" "$WANTS_DIR/ehc602.service"
    echo "Servizio ehc602 installato e abilitato."
    # Segnala a patch.sh che serve un riavvio
    touch /tmp/.patch_reboot_needed
fi

# --- Rimuovi e disabilita i vecchi script init.d ---
# Il vecchio file si chiama 'ehc602' o 'ehc' (campo Provides dello script init.d)

for NAME in ehc602 ehc; do
    INITD_FILE="/etc/init.d/$NAME"
    if [ -f "$INITD_FILE" ]; then
        echo "Trovato script init.d: $INITD_FILE. Disabilitazione e rimozione in corso..."
        update-rc.d -f "$NAME" remove
        rm -f "$INITD_FILE"
        echo "Script init.d '$NAME' rimosso."
    fi
done
