#!/bin/sh

# Static IP Configuration
IP_ADDRESS="192.168.15.200"
NETMASK="255.255.255.0"
GATEWAY="192.168.15.1"
DNS_SERVER="8.8.8.8"

# Path to Python server
SERVER_SCRIPT="/usr/bin/server.py"
LOG_FILE="/var/log/server.log"

MAX_TRIES=10
TRIES=0

check_ip_address() {
    if ifconfig eth0 | grep -q "inet "; then
        return 0
    else
        return 1
    fi
}

set_static_ip() {
    echo "Setting static IP $IP_ADDRESS"
    ifconfig eth0 $IP_ADDRESS netmask $NETMASK
    route add default gw $GATEWAY
    echo "nameserver $DNS_SERVER" > /etc/resolv.conf
    ifconfig eth0 up
}

start_server() {
    echo "Starting Python server..."
    # Redirect both stdout and stderr to log file
    /usr/bin/python3 $SERVER_SCRIPT >> $LOG_FILE 2>&1 &
    echo "Server started, logs at $LOG_FILE"
}

stop_server() {
    echo "Stopping Python server..."
    pkill -f "python3 $SERVER_SCRIPT"
}

case "$1" in
    start)
        echo "Starting services..."
        
        # Wait for network
        while [ $TRIES -lt $MAX_TRIES ]; do
            if check_ip_address; then
                set_static_ip
                start_server
                exit 0
            else
                echo "Waiting for network... (Attempt $((TRIES + 1))/$MAX_TRIES)"
                TRIES=$((TRIES + 1))
                sleep 3
            fi
        done
        
        echo "Failed to initialize network"
        exit 1
        ;;
    stop)
        stop_server
        ;;
    restart)
        stop_server
        sleep 2
        start_server
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac

exit 0