#!/bin/bash

# Log file
log_file="/var/log/watchdog.log"

# Configuration file
config_file="/etc/watchdog.conf"

# Function to log messages with timestamp
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$log_file"
}

# Function to update watchdog configuration
update_watchdog_config() {
    # Extract watchdog IP addresses
    watchdog=$(sudo cat /var/lib/dhcp/* | grep -a "option watchdog" | tail -1 | \
    awk '{for (i=3; i<=NF; i++) printf "%s ", $i}' | tr -d '";')
    
    IFS=', ' read -r -a ip_array <<< "$watchdog"  # Split IPs by comma or space

    # Backup current configuration
    sudo cp "$config_file" "$config_file.bak"
    log "Backup of $config_file created successfully."

    # Write static configuration to file
    {
        echo "realtime = yes"
        echo "priority = 1"
        echo "interface = eth0"
        echo "interval = 58"
        echo "ping-count = 1"
    } | sudo tee "$config_file" > /dev/null
    log "Static configuration written to $config_file."

    if [ ${#ip_array[@]} -eq 0 ]; then
        log "No IP addresses found. Watchdog configuration cleared."
        return 1  # No IP addresses to configure
    else
        # Append IPs to config
        for ip in "${ip_array[@]}"; do
            echo "ping = $ip" | sudo tee -a "$config_file" > /dev/null
        done
        log "Configured watchdog to ping: ${ip_array[*]}"

        # Attempt to restart watchdog service
        if ! sudo systemctl restart watchdog; then
            log "Failed to restart watchdog service. Attempting to stop and start."

            # Fallback: stop then start the service
            sudo systemctl stop watchdog
            if sudo systemctl start watchdog; then
                log "Watchdog service started successfully after stop."
            else
                log "Failed to start watchdog service after stop."
                return 1
            fi
        else
            log "Watchdog service restarted successfully."
        fi

        # Stop watchdog-monitor service if restart/start was successful
        if sudo systemctl stop watchdog-monitor; then
            log "watchdog-monitor service stopped successfully."
        else
            log "Failed to stop watchdog-monitor service."
        fi

        return 0  # Successful restart/start
    fi
}

# Loop parameters
interval=30  # Interval to wait between checks
start_time=$(date +%s)
end_time=$((start_time + 300))  # 5 minutes in seconds

# Main loop
while true; do
    if ! update_watchdog_config; then
        log "IP addresses found and watchdog restarted. Exiting loop."
        break
    else
        log "No IP addresses found or restart failed. Waiting for $interval seconds before checking again..."
    fi

    # Check if 5 minutes have passed
    if [ "$(date +%s)" -ge "$end_time" ]; then
        log "5 minutes have passed. Stopping the watchdog service."
        sudo systemctl stop watchdog
        break
    fi

    log "Waiting for $interval seconds before checking for IP addresses again..."
    sleep $interval
done

# Version 1.5:
# Created 2024 by Tim Eertmoed @ WiS IT-Solutions GmbH, Germany to work on Raspian as custom PXE init script.
