#!/bin/bash
LOG_DIR="/var/log/tesm"
LOGFILE="$LOG_DIR/live.log"
mkdir -p "$LOG_DIR"
touch "$LOGFILE"

SLEEP=$(python3 - <<'END'
import sqlite3
conn = sqlite3.connect("/srv/tesm/sqlite.db")
row = conn.execute("SELECT value FROM settings WHERE key='check_interval'").fetchone()
conn.close()
print(row[0] if row else 300)
END
)

SLEEP=${SLEEP:-300}

function disable_poe() {
    local switch_ip=$1
    local switch_port=$2
    local username=$3
    local password=$4
    local ssh_port=${5:-22}
    expect <<EOF
set timeout 5
spawn ssh -p $ssh_port $username@$switch_ip
expect {
    "assword:" { send "$password\r"; exp_continue }
    "Press any key" { send "\r"; exp_continue }
    -re ".*> $" { }
}
send "configure terminal\r"
expect "(config)#"
send "interface $switch_port\r"
expect "(eth-$switch_port)#"
send "no power-over-ethernet\r"
expect "(eth-$switch_port)#"
send "exit\r"
expect "(config)#"
send "exit\r"
expect "#"
send "exit\r"
expect ">"; send "exit\r"
expect "Do you want to log out (y/n)?" { send "y\r" }
expect eof
EOF
}

function enable_poe() {
    local switch_ip=$1
    local switch_port=$2
    local username=$3
    local password=$4
    local ssh_port=${5:-22}
    expect <<EOF
set timeout 5
spawn ssh -p $ssh_port $username@$switch_ip
expect {
    "assword:" { send "$password\r"; exp_continue }
    "Press any key" { send "\r"; exp_continue }
    -re ".*> $" { }
}
send "configure terminal\r"
expect "(config)#"
send "interface $switch_port\r"
expect "(eth-$switch_port)#"
send "power-over-ethernet\r"
expect "(eth-$switch_port)#"
send "exit\r"
expect "(config)#"
send "exit\r"
expect "#"
send "exit\r"
expect ">"; send "exit\r"
expect "Do you want to log out (y/n)?" { send "y\r" }
expect eof
EOF
}

function check_device() {
    local rpi_ip=$1 dev_name=$2 switch_ip=$3 switch_ssh_port=$4
    local switch_hostname=$5 switch_port=$6 switch_user=$7 switch_pass=$8
    local license_active=$9

    if ping -c 1 -W 2 "$rpi_ip" &> /dev/null; then
        echo "$(date '+%Y-%m-%d %H:%M:%S') $dev_name ist erreichbar!" >> "$LOGFILE"
        return
    fi

    echo "$(date '+%Y-%m-%d %H:%M:%S') $dev_name ist nicht erreichbar!" >> "$LOGFILE"

    if [ -z "$switch_ip" ] || [ -z "$switch_port" ] || [ "$switch_port" == "None" ]; then
        return
    fi

    # Automatischer PoE-Neustart bei Ausfall ist ein lizenzpflichtiges
    # Feature (siehe Lizenzsystem) -- der manuelle Neustart-Button im
    # Dashboard (manual_restart() weiter unten) ruft disable_poe/enable_poe
    # dagegen IMMER direkt auf und bleibt davon bewusst unberührt.
    if [ "$license_active" != "1" ]; then
        echo "$(date '+%Y-%m-%d %H:%M:%S') $dev_name: automatischer PoE-Neustart übersprungen -- keine gültige Lizenz." >> "$LOGFILE"
        return
    fi

    if ! disable_poe "$switch_ip" "$switch_port" "$switch_user" "$switch_pass" "$switch_ssh_port"; then
        echo "$(date '+%Y-%m-%d %H:%M:%S') $dev_name: Switch $switch_hostname nicht erreichbar oder Kommando abgelehnt — PoE-Deaktivierung fehlgeschlagen, kein Neustart durchgeführt." >> "$LOGFILE"
        return
    fi
    echo "$(date '+%Y-%m-%d %H:%M:%S') $dev_name PoE auf Port $switch_port am Switch $switch_hostname deaktiviert." >> "$LOGFILE"

    sleep 2

    if ! enable_poe "$switch_ip" "$switch_port" "$switch_user" "$switch_pass" "$switch_ssh_port"; then
        echo "$(date '+%Y-%m-%d %H:%M:%S') $dev_name: Switch $switch_hostname nicht erreichbar oder Kommando abgelehnt — PoE-Reaktivierung fehlgeschlagen! Port bleibt ggf. deaktiviert." >> "$LOGFILE"
        return
    fi
    echo "$(date '+%Y-%m-%d %H:%M:%S') $dev_name PoE auf Port $switch_port am Switch $switch_hostname aktiviert." >> "$LOGFILE"
}

function manual_restart() {
    local target_mac="$1"
    python3 /srv/tesm/generate_ips.py | while IFS='|' read -r rpi_ip dev_name switch_ip switch_ssh_port switch_hostname switch_port switch_user switch_pass mac; do
        if [[ "$mac" != "$target_mac" ]]; then
            continue
        fi
        echo "$(date '+%Y-%m-%d %H:%M:%S') Manueller Neustart von $dev_name gestartet." >> "$LOGFILE"
        if [ -n "$switch_ip" ] && [ -n "$switch_port" ] && [ "$switch_port" != "None" ]; then
            if ! disable_poe "$switch_ip" "$switch_port" "$switch_user" "$switch_pass" "$switch_ssh_port"; then
                echo "$(date '+%Y-%m-%d %H:%M:%S') $dev_name: Switch $switch_hostname nicht erreichbar oder Kommando abgelehnt — manueller Neustart abgebrochen." >> "$LOGFILE"
                exit 1
            fi
            echo "$(date '+%Y-%m-%d %H:%M:%S') $dev_name PoE deaktiviert." >> "$LOGFILE"
            sleep 2
            if ! enable_poe "$switch_ip" "$switch_port" "$switch_user" "$switch_pass" "$switch_ssh_port"; then
                echo "$(date '+%Y-%m-%d %H:%M:%S') $dev_name: Switch $switch_hostname nicht erreichbar oder Kommando abgelehnt — PoE-Reaktivierung fehlgeschlagen! Port bleibt ggf. deaktiviert." >> "$LOGFILE"
                exit 1
            fi
            echo "$(date '+%Y-%m-%d %H:%M:%S') $dev_name PoE aktiviert." >> "$LOGFILE"
            echo "$(date '+%Y-%m-%d %H:%M:%S') Manueller Neustart von $dev_name abgeschlossen." >> "$LOGFILE"
        else
            echo "$(date '+%Y-%m-%d %H:%M:%S') $dev_name besitzt keinen PoE-Port." >> "$LOGFILE"
        fi
        exit 0
    done
}

if [[ "$1" == "restart" ]]; then
    if [[ -z "$2" ]]; then
        echo "MAC-Adresse fehlt."
        exit 1
    fi
    manual_restart "$2"
    exit 0
fi

while true; do
    echo "--------------------------------------------------------------------" >> "$LOGFILE"

    # Einmal pro Schleifendurchlauf gelesen (wie SLEEP oben beim Skriptstart),
    # nicht pro Gerät -- reicht als Shell-Variable an check_device() durch.
    LICENSE_ACTIVE=$(python3 - <<'END'
import sys
sys.path.insert(0, "/srv/tesm")
from app import license_active
print("1" if license_active() else "0")
END
)
    LICENSE_ACTIVE=${LICENSE_ACTIVE:-0}

    while IFS='|' read -r rpi_ip dev_name switch_ip switch_ssh_port switch_hostname switch_port switch_user switch_pass mac; do
        check_device "$rpi_ip" "$dev_name" "$switch_ip" "$switch_ssh_port" "$switch_hostname" "$switch_port" "$switch_user" "$switch_pass" "$LICENSE_ACTIVE" &
    done < <(python3 /srv/tesm/generate_ips.py)

    wait
    sleep "$SLEEP"
done
