#!/bin/bash
set -e

echo "======================================"
echo " openSUSE Cloud-Init + Static IP Setup "
echo "======================================"

# ========= SSH KEY (CHANGE THIS) =========
SSH_KEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBIOiEO5YP5btmAIdpwhtSzwWuAfQ8ZJfluEVEwxhqY2 mbp-office"

# ========= Detect Active Network Interface =========
IFACE=$(ip route | awk '/default/ {print $5}' | head -n 1)

if [ -z "$IFACE" ]; then
  echo "ERROR: Could not detect network interface."
  exit 1
fi

echo "Detected Interface: $IFACE"

# ========= Ask For Network Info =========
read -p "Enter Static IP (example: 103.174.50.10): " STATIC_IP
read -p "Enter CIDR (example: 24): " CIDR
read -p "Enter Gateway (example: 103.174.50.1): " GATEWAY
read -p "Enter Primary DNS (default: 8.8.8.8): " DNS1
read -p "Enter Secondary DNS (default: 1.1.1.1): " DNS2

DNS1=${DNS1:-8.8.8.8}
DNS2=${DNS2:-1.1.1.1}

echo
echo "Applying Configuration:"
echo "IP: $STATIC_IP/$CIDR"
echo "Gateway: $GATEWAY"
echo "DNS: $DNS1, $DNS2"
echo

read -p "Proceed? (yes/no): " CONFIRM
[ "$CONFIRM" != "yes" ] && exit 0

# ========= Install Cloud-Init =========
echo "[1/6] Installing Cloud-Init..."
zypper refresh
zypper install -y cloud-init 

# ========= Enable Cloud-Init Services =========
echo "[2/6] Enabling Cloud-Init Services..."
systemctl enable cloud-init
systemctl enable cloud-init-local
systemctl enable cloud-config
systemctl enable cloud-final

# ========= Configure Static Network (Wicked) =========
echo "[3/6] Configuring Static Network..."

CFG_FILE="/etc/sysconfig/network/ifcfg-${IFACE}"

cat > "$CFG_FILE" <<EOF
BOOTPROTO='static'
STARTMODE='auto'
IPADDR='${STATIC_IP}/${CIDR}'
GATEWAY='${GATEWAY}'
DNS1='${DNS1}'
DNS2='${DNS2}'
EOF

systemctl restart wicked

# ========= Install SSH Key =========
echo "[4/6] Installing SSH Key..."

mkdir -p /root/.ssh
chmod 700 /root/.ssh

echo "$SSH_KEY" > /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys

# ========= Clean Template Identity =========
echo "[5/6] Cleaning Machine ID and SSH Host Keys..."

truncate -s 0 /etc/machine-id
rm -f /var/lib/dbus/machine-id
rm -f /etc/udev/rules.d/70-persistent-net.rules
rm -f /etc/ssh/ssh_host_*

# ========= Final Cloud-Init Reset =========
echo "[6/6] Resetting Cloud-Init..."

cloud-init clean

echo
echo "✅ SETUP COMPLETE"
echo "--------------------------------------"
echo "Static IP Applied: $STATIC_IP/$CIDR"
echo "Gateway: $GATEWAY"
echo "SSH Key Installed for root"
echo "Cloud-Init Ready"
echo
echo "⚠️  REBOOT REQUIRED:"
echo "    reboot"
echo "--------------------------------------"

