#!/bin/bash

if [ "$EUID" -ne 0 ]; then
    echo "Must be run as root. Exiting."
    exit 1
fi

read -n 1 -p "With or without watchdog? (y/n)" input

case $input in
    y)
        echo "Installing watchdog..."
        # Copy watchdog file
        cat > /home/pi/watchdog.py << EOF
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import logging

GPIO.setmode(GPIO.BCM)
GPIO.setup(27, GPIO.OUT)

while True:
    GPIO.output(27, GPIO.HIGH)
    time.sleep(0.1)
    logging.warning("ping!")
    GPIO.output(27, GPIO.LOW)
    time.sleep(10)
EOF
        chmod +x /home/pi/watchdog.py
        cat > /etc/systemd/system/hwwatchdog.service << EOF
[Unit]
Description=Hardware Watchdog
After=network.target

[Service]
ExecStart=/home/pi/watchdog.py
Restart=always

[Install]
WantedBy=multi-user.target
EOF
        systemctl daemon-reload
        systemctl enable --now hwwatchdog
        echo "Watchdog installed"
        ;;
    *)
        echo "Skipping watchdog."
        ;;
esac

echo "Installing rebooter..."
cat > /home/pi/rebooter.sh << 'EOF'
#!/bin/bash

file_path="/home/pi/reboots"

# Check if file exists, if not create it with content "0"
if [ ! -f "$file_path" ]; then
  echo "0" > "$file_path"
fi

# Read content, increment by 1, write back
content=$(cat "$file_path")
((content++))
echo "$content" > "$file_path"

# Reboot
/usr/sbin/shutdown -r now
EOF
chmod +x /home/pi/rebooter.sh
# schedule as root if this command is run as root
(crontab -l 2>/dev/null; echo "*/5 * * * * /home/pi/rebooter.sh") | crontab -

echo "Rebooter installed"
echo "Installation completed!"

