#!/bin/bash

# --- k3OS Automated Static IP Configuration Script ---

# Check if the script is run as root
if [ "$EUID" -ne 0 ]; then
  echo "Please run this script with sudo."
  exit 1
fi

echo "--- Static IP Configuration for k3OS ---"

# --- 1. Automatically Detect Network Interface ---
# The primary interface is typically the one associated with the default gateway.
IFACE=$(ip route | grep default | awk '{print $5}' | head -n 1)

if [ -z "$IFACE" ]; then
  echo "Error: Could not automatically detect a primary network interface."
  echo "Please identify the correct interface name (e.g., eth0, enp0s3) and run the script again."
  exit 1
fi

echo "Automatically detected primary interface: $IFACE"
echo ""

# --- 2. Prompt for IP Details ---
read -p "Enter the Static IPv4 Address (e.g., 192.168.1.100): " IP_ADDR
read -p "Enter the Netmask (e.g., 255.255.255.0): " NETMASK
read -p "Enter the Gateway IP Address (e.g., 192.168.1.1): " GATEWAY
read -p "Enter the Nameserver (e.g., 1.1.1.1): " NAMESERVERS

# --- 3. Format ConnMan IPv4 String ---
# ConnMan's IPv4 format: <IP>/<NETMASK_LONG>/<GATEWAY>
IPV4_CONFIG="${IP_ADDR}/${NETMASK}/${GATEWAY}"

# --- 4. Generate and Write Configuration File ---
CONFIG_FILE="/var/lib/connman/default.config"

# Create the file content
CONNMAN_CONFIG="[service_${IFACE}]
Type=ethernet
IPv4=${IPV4_CONFIG}
IPv6=off
Nameservers=${NAMESERVERS}"

echo ""
echo "--- Generated Configuration ---"
echo "$CONNMAN_CONFIG"
echo "-------------------------------"

# Write to the file
echo "$CONNMAN_CONFIG" | sudo tee "$CONFIG_FILE" > /dev/null

if [ $? -eq 0 ]; then
  echo "Successfully wrote static IP configuration for **$IFACE** to $CONFIG_FILE"
  echo "You must now **reboot** the system for the changes to take effect."
  echo "   (Run: 'sudo reboot')"
else
  echo "Error writing to $CONFIG_FILE. "
fi