#!/bin/bash
set -e

# Try to find the USB Ethernet interface first
iface=$(ip -o link | awk -F': ' '/enx|enp.*u/{print $2}' | head -n 1)

# If no USB interface, fall back to eth0
if [ -z "$iface" ]; then
	if ip link show eth0 &>/dev/null; then
		iface="eth0"
		echo "USB Ethernet not found. Using eth0."
	else
		echo "No suitable interface found."
		exit 1
	fi
else
	echo "Using USB Ethernet interface: $iface"
fi

# Bring interface up before assigning IP
sudo ip link set "$iface" up

# Assign IP address if not already set
if ! ip addr show dev "$iface" | grep -q "192.168.192.10"; then
	sudo ip addr add 192.168.192.10/24 dev "$iface"
fi

# Scan port 9100 on the printer IP and verify it is open
if ! nmap -p 9100 --open 192.168.192.168 | grep -q "9100/tcp open"; then
	echo "Printer port 9100 is not open."
	exit 1
fi

