#!/bin/sh

INTERFACE="eth0"
PIDFILE="/var/run/udhcpc.pid"

check_interface() {
    if ip link show "$INTERFACE" >/dev/null 2>&1; then
        echo "Interface $INTERFACE found"
        return 0
    else
        echo "Interface $INTERFACE not found"
        return 1
    fi
}

kill_all_udhcpc() {
    echo "Checking for existing udhcpc processes..."
    PIDS=$(pgrep -f "udhcpc.*$INTERFACE")
    if [ -n "$PIDS" ]; then
        echo "Killing existing udhcpc processes: $PIDS"
        kill $PIDS 2>/dev/null
        sleep 1
        PIDS=$(pgrep -f "udhcpc.*$INTERFACE")
        if [ -n "$PIDS" ]; then
            echo "Force killing remaining processes: $PIDS"
            kill -9 $PIDS 2>/dev/null
        fi
    fi
    rm -f "$PIDFILE"
}

start_udhcpc() {
    kill_all_udhcpc
    
    echo "Starting udhcpc on $INTERFACE..."
    udhcpc -i "$INTERFACE" -b -p "$PIDFILE"
    
    if [ $? -eq 0 ]; then
        echo "udhcpc started successfully"
        return 0
    else
        echo "Failed to start udhcpc"
        return 1
    fi
}

stop_udhcpc() {
    kill_all_udhcpc
    echo "All udhcpc processes stopped"
}

case "$1" in
    start)
        if check_interface; then
            start_udhcpc
        else
            echo "Cannot start udhcpc: interface $INTERFACE not available"
            exit 1
        fi
        ;;
    stop)
        stop_udhcpc
        ;;
    restart)
        stop_udhcpc
        sleep 1
        if check_interface; then
            start_udhcpc
        else
            echo "Cannot restart udhcpc: interface $INTERFACE not available"
            exit 1
        fi
        ;;
    status)
        if [ -f "$PIDFILE" ]; then
            PID=$(cat "$PIDFILE")
            if kill -0 "$PID" >/dev/null 2>&1; then
                echo "udhcpc is running (PID: $PID)"
            else
                echo "udhcpc is not running (stale pidfile)"
            fi
        else
            echo "udhcpc is not running"
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac
