#!/bin/bash

# Standardwerte setzen
FQDN=""
ADDR=""
GW=""
NS=""
USE_DHCP=0
IFACE="enp0s3"

# Optionen mit getopts parsen
while getopts "f:a:g:n:d" opt; do
  case $opt in
    f) FQDN="$OPTARG" ;;
    a) ADDR="$OPTARG" ;;
    g) GW="$OPTARG" ;;
    n) NS="$OPTARG" ;;
    d) USE_DHCP=1 ;;
    *) echo "Ungültige Option" >&2; exit 1 ;;
  esac
done

# Gültigkeit prüfen
if [[ -z "$FQDN" ]]; then
  echo "Fehlender FQDN! Nutzung:"
  echo "$0 -f <FQDN> [-d | -a <IP/CIDR> -g <Gateway> -n <Nameserver>]"
  exit 1
fi

if (( USE_DHCP == 1 )); then
  if [[ -n "$ADDR" || -n "$GW" || -n "$NS" ]]; then
    echo "Fehler: -d darf nicht mit -a, -g oder -n kombiniert werden." >&2
    exit 1
  fi
else
  if [[ -z "$ADDR" || -z "$GW" || -z "$NS" ]]; then
    echo "Fehlende Argumente für statische Konfiguration! Nutzung:"
    echo "$0 -f <FQDN> [-d | -a <IP/CIDR> -g <Gateway> -n <Nameserver>]"
    exit 1
  fi
fi


# Hostname setzen
hostnamectl set-hostname "$FQDN"

# Alte NM-Verbindung löschen
nmcli connection delete "$IFACE" >/dev/null 2>&1

# DHCP-Konfiguration
if (( USE_DHCP == 1 )); then
  nmcli connection add type ethernet ifname "$IFACE" con-name "$IFACE" ipv4.method auto ipv6.method ignore
else
  # Statische Konfiguration
  nmcli connection add type ethernet ifname "$IFACE" con-name "$IFACE" \
    ipv4.method manual \
    ipv4.addresses "$ADDR" \
    ipv4.gateway "$GW" \
    ipv4.dns "$NS" \
    ipv6.method ignore
fi

# Verbindung aktivieren
nmcli connection up "$IFACE"
if [[  ! -f /etc/pki/ca-trust/source/anchors/fake-ca.crt ]]
cat<<HERE >  /etc/pki/ca-trust/source/anchors/fake-ca.crt
NOTHING
HERE
if [[ cat  /etc/pki/ca-trust/source/anchors/fake-ca.crt == "NOTHING ]]
then
exit
else
sudo update-ca-trust
fi
