#!/bin/sh

WATCHDOG_SCRIPT="/etc/kvmd/user/scripts/rtty-loop.sh"

start() {
    # Check if watchdog script is already running
    if pgrep -f "$WATCHDOG_SCRIPT" > /dev/null; then
        echo "selfHosted cloud is already started"
        return 0
    fi
    echo "starting self hosted cloud"
    
    # Create turnserver.json configuration
    cat <<EOF > /tmp/turnserver.json
{
    "username": "JK5X5EbZ2DmLdy0ygJeqG6eZCav68BvS",
    "ttl": 864000,
    "password": "3kUdWh7XJQ3CPcth1cutS86FrDV2tEuP",
    "uris": [
        "turn:106.55.158.199:3478?transport=udp",
        "turn:106.55.158.199:3478?transport=tcp"
    ]
}
EOF

    # Read device information
    device_id=$(cat /proc/gl-hw-info/device_ddns)
    device_mac=$(cat /proc/gl-hw-info/device_mac)
    
    # Ensure the directory exists
    mkdir -p "$(dirname "$WATCHDOG_SCRIPT")"
    
    # Write the watchdog script content
    cat <<EOF > "$WATCHDOG_SCRIPT"
#!/bin/sh
device_id=\$(cat /proc/gl-hw-info/device_ddns)
device_mac=\$(cat /proc/gl-hw-info/device_mac)
while true; do
    if ! pgrep -f "rtty.*-d \$device_mac" > /dev/null; then
        echo "[\$(date)] rtty not running, starting..."
        rtty -sx -T 2 -I "\$device_id" -h 106.55.158.199:5912 -t 12tBwAsxMVDUd6BqbTErBEZbG56sotvw -d "\$device_mac" &
    fi
    sleep 5
done
EOF
    
    chmod +x "$WATCHDOG_SCRIPT"
    nohup "$WATCHDOG_SCRIPT" 2>/dev/null &
    echo "started selfHosted cloud"
}

stop() {
    echo "stopping selfHosted cloud"
    
    # Read device information
    device_id=$(cat /proc/gl-hw-info/device_ddns)
    device_mac=$(cat /proc/gl-hw-info/device_mac)
    
    # Kill existing rtty instances and previous watchdog process
    pkill -f "$WATCHDOG_SCRIPT"
    pkill -f "rtty.*-d $device_mac"
    
    echo "stopped selfHosted cloud"
}

restart() {
    stop
    sleep 1
    start
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart|reload)
        restart
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?