#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.installer
# SPDX-Security-Contact: security@coresecret.eu

guard_sourcing

#######################################
# Setup network.
# Globals:
#   DIR_BAK
#   TARGET
#   VAR_FINAL_FQDN
#   VAR_FINAL_IPV4
#   VAR_FINAL_IPV4_GW
#   VAR_FINAL_IPV4_SUBNET
#   VAR_FINAL_IPV6
#   VAR_FINAL_NIC
#   VAR_LINK_IPV6
#   network_autoconfig_enable
#   network_choose_interface_auto
#   network_choose_interface_static
#   network_hostname
#   network_static_ipv4address
#   network_static_ipv4gateway
#   network_static_ipv4nameserver_0
#   network_static_ipv4nameserver_1
#   network_static_ipv4nameserver_2
#   network_static_ipv4nameserver_fallback_0
#   network_static_ipv4nameserver_fallback_1
#   network_static_ipv4netmask
#   network_static_ipv6address
#   network_static_ipv6gateway
#   network_static_ipv6nameserver_0
#   network_static_ipv6nameserver_1
#   network_static_ipv6nameserver_2
#   network_static_ipv6nameserver_fallback_0
#   network_static_ipv6nameserver_fallback_1
#   network_static_ipv6netmask
# Arguments:
#  None
# Returns:
#   0: on success
#######################################
setup_network() {
  do_in_target "${TARGET}" apt-get install -y isc-dhcp-client ifupdown
  mkdir -p "${TARGET}/etc/network/interfaces/interfaces.d"

  declare var_auto_nic="" var_auto_ipv4_ccidr="" var_auto_ipv4_subnet="" var_auto_ipv4="" var_auto_ipv4_gw="" \
    var_auto_ipv6_ccidr="" var_auto_ipv6="" var_auto_ipv6_gw="" var_link_ipv4="" var_link_ipv6="" var_auto_fqdn="" ns=""
  declare -a ary_ipv4_ns ary_ipv6_ns

  ary_ipv4_ns+=("${network_static_ipv4nameserver_0}")
  [[ -n "${network_static_ipv4nameserver_1}" ]] && ary_ipv4_ns+=("${network_static_ipv4nameserver_1}")
  [[ -n "${network_static_ipv4nameserver_2}" ]] && ary_ipv4_ns+=("${network_static_ipv4nameserver_2}")
  [[ -n "${network_static_ipv4nameserver_fallback_0}" ]] && ary_ipv4_ns+=("${network_static_ipv4nameserver_fallback_0}")
  [[ -n "${network_static_ipv4nameserver_fallback_1}" ]] && ary_ipv4_ns+=("${network_static_ipv4nameserver_fallback_1}")

  ary_ipv6_ns+=("${network_static_ipv6nameserver_0}")
  [[ -n "${network_static_ipv6nameserver_1}" ]] && ary_ipv6_ns+=("${network_static_ipv6nameserver_1}")
  [[ -n "${network_static_ipv6nameserver_2}" ]] && ary_ipv6_ns+=("${network_static_ipv6nameserver_2}")
  [[ -n "${network_static_ipv6nameserver_fallback_0}" ]] && ary_ipv6_ns+=("${network_static_ipv6nameserver_fallback_0}")
  [[ -n "${network_static_ipv6nameserver_fallback_1}" ]] && ary_ipv6_ns+=("${network_static_ipv6nameserver_fallback_1}")

  ### Check current network connection and configure variables
  var_auto_nic=$(ip -o link show | awk -F': ' '/state UP/ && $2!="lo" {print $2; exit}')
  var_auto_ipv4_ccidr=$(ip -4 -o addr show "${var_auto_nic}" | awk '{print $4; exit}')
  var_auto_ipv4_subnet=$(generate_subnetmask "${var_auto_ipv4_ccidr}")
  var_auto_ipv4=$(echo "${var_auto_ipv4_ccidr}" | awk -F'/' '{print $1}')
  var_auto_ipv4_gw=$(ip route show default dev "${var_auto_nic}" | awk '/^default/ {print $3; exit}')
  var_auto_ipv6_ccidr=$(ip -6 -o addr show "${var_auto_nic}" | awk '/scope global/ {print $4; exit}')
  if [[ -n "${var_auto_ipv6_ccidr}" ]]; then
    var_auto_ipv6=$(echo "${var_auto_ipv6_ccidr}" | awk -F'/' '{print $1}')
    var_auto_ipv6_gw=$(ip -6 route show default dev "${var_auto_nic}" | awk '/^default/ {print $3; exit}')
  fi
  var_link_ipv4=$(ping -q -c 1 -W 1 -4 debian.org > /dev/null 2>&1 && echo "true" || echo "false")
  var_link_ipv6=$(ping -q -c 1 -W 1 -6 debian.org > /dev/null 2>&1 && echo "true" || echo "false")
  if [[ -f "/var/lib/dhcp/dhclient.${var_auto_nic}.leases" ]]; then
    var_auto_fqdn=$(grep -m1 'option host-name' "/var/lib/dhcp/dhclient.${var_auto_nic}.leases" | sed -E 's/.*"([^"]+)".*/\1/')
  else
    var_auto_fqdn=""
  fi

  do_log "info" "false" "Live environment network check: Auto NIC          ='${var_auto_nic}'."
  do_log "info" "false" "Live environment network check: Auto IPv4         ='${var_auto_ipv4}'."
  do_log "info" "false" "Live environment network check: Auto IPv4 CCIDR   ='${var_auto_ipv4_ccidr}'."
  do_log "info" "false" "Live environment network check: Auto IPv4 Subnet  ='${var_auto_ipv4_subnet}'."
  do_log "info" "false" "Live environment network check: Auto IPv4 Gateway ='${var_auto_ipv4_gw}'."
  do_log "info" "false" "Live environment network check: Auto IPv6         ='${var_auto_ipv6}'."
  do_log "info" "false" "Live environment network check: Auto IPv6 CCIDR   ='${var_auto_ipv6_ccidr}'."
  do_log "info" "false" "Live environment network check: Auto IPv6 Gateway ='${var_auto_ipv6_gw}'."
  do_log "info" "false" "Live environment network check: Auto IPv4 Link    ='${var_link_ipv4}'."
  do_log "info" "false" "Live environment network check: Auto IPv6 Link    ='${var_link_ipv6}'."
  do_log "info" "false" "Live environment network check: Auto FQDN         ='${var_auto_fqdn}'."

  ### Create network configuration file header.
  if [[ -f "${TARGET}/etc/network/interfaces" ]]; then
    mkdir -p "${DIR_BAK}/etc/network"
    mv "${TARGET}/etc/network/interfaces" "${DIR_BAK}/etc/network/interfaces.bak"
    do_log "info" "false" "Existing '${TARGET}/etc/network/interfaces' moved."
  fi

  cat << EOF >| "${TARGET}/etc/network/interfaces"
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.installer
# SPDX-Security-Contact: security@coresecret.eu

# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
EOF
  chmod 0644 "${TARGET}/etc/network/interfaces"
  do_log "info" "false" "Header '${TARGET}/etc/network/interfaces' created."

  ### Configure network interfaces based on 'preseed.yaml' and create network configuration files for IPv4.
  if [[ "${network_autoconfig_enable,,}" == "true" && "${network_choose_interface_auto,,}" == "true" ]]; then

    ### Reminder ###
    # auto:
    # For servers or systems with static interfaces that should always be available (e.g., eth0 on a server).
    # For configurations where the interface should be active regardless of the cable status.
    # allow-hotplug:
    # For systems with dynamic or removable network devices (e.g., laptops or USB adapters).
    # To avoid boot delays when interfaces are unavailable.

    cat << EOF >| "${TARGET}/etc/network/interfaces/interfaces.d/10-ipv4-dhcp"
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.installer
# SPDX-Security-Contact: security@coresecret.eu

# The primary network interface IPv4
auto ${var_auto_nic}
iface ${var_auto_nic} inet dhcp

# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
EOF
    chmod 0644 "${TARGET}/etc/network/interfaces/interfaces.d/10-ipv4-dhcp"
    do_log "info" "false" "IPv4 on the primary NIC: '${var_auto_nic}' configured with DHCP."

  elif [[ "${network_autoconfig_enable,,}" == "true" && "${network_choose_interface_auto,,}" == "false" ]]; then

    cat << EOF >| "${TARGET}/etc/network/interfaces/interfaces.d/10-ipv4-dhcp"
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.installer
# SPDX-Security-Contact: security@coresecret.eu

# The primary network interface IPv4
auto ${network_choose_interface_static}
iface ${network_choose_interface_static} inet dhcp

# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
EOF
    chmod 0644 "${TARGET}/etc/network/interfaces/interfaces.d/10-ipv4-dhcp"
    do_log "info" "false" "IPv4 on the primary NIC: '${network_choose_interface_static}' configured with DHCP."

  fi

  if [[ "${network_autoconfig_enable,,}" == "false" ]]; then

    cat << EOF >| "${TARGET}/etc/network/interfaces/interfaces.d/10-ipv4-static"
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.installer
# SPDX-Security-Contact: security@coresecret.eu

# The primary network interface IPv4
auto ${network_choose_interface_static}
iface ${network_choose_interface_static} inet static
    address ${network_static_ipv4address}
    netmask ${network_static_ipv4netmask}
    gateway ${network_static_ipv4gateway}
    dns-nameservers ${ary_ipv4_ns[*]}

# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
EOF
    chmod 0644  "${TARGET}/etc/network/interfaces/interfaces.d/10-ipv4-static"
    do_log "info" "false" "IPv4 on the primary NIC: '${network_choose_interface_static}' configured statically."

  fi

  ### Configure network interfaces based on 'preseed.yaml' and create network configuration files for IPv6.
  if [[ "${network_autoconfig_enable,,}" == "true" && "${var_link_ipv6,,}" == "true" ]]; then

    cat << EOF >| "${TARGET}/etc/network/interfaces/interfaces.d/10-ipv6-dhcp"
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.installer
# SPDX-Security-Contact: security@coresecret.eu

# The primary network interface IPv6
auto ${var_auto_nic}
iface ${var_auto_nic} inet6 dhcp

# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
EOF
    chmod 0644 "${TARGET}/etc/network/interfaces/interfaces.d/10-ipv6-dhcp"
    do_log "info" "false" "IPv6 on the primary NIC: '${var_auto_nic}' configured with DHCP."

  fi

  if [[ "${network_autoconfig_enable,,}" == "false" && -n "${network_static_ipv6address}" ]]; then

    cat << EOF >| "${TARGET}/etc/network/interfaces/interfaces.d/10-ipv6-static"
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.installer
# SPDX-Security-Contact: security@coresecret.eu

# The primary network interface IPv6
auto ${network_choose_interface_static}
iface ${network_choose_interface_static} inet6 static
    address ${network_static_ipv6address}/${network_static_ipv6netmask}
    gateway ${network_static_ipv6gateway}
    dns-nameservers ${ary_ipv6_ns[*]}

# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
EOF
    chmod 0644 "${TARGET}/etc/network/interfaces/interfaces.d/10-ipv6-static"
    do_log "info" "false" "IPv6 on the primary NIC: '${network_choose_interface_static}' configured statically."

  fi

  if [[ -f "${TARGET}/etc/resolv.conf" ]]; then
    mkdir -p "${DIR_BAK}/etc"
    mv "${TARGET}/etc/resolv.conf" "${DIR_BAK}/etc/resolv.conf.bak"
    do_log "info" "false" "Existing '${TARGET}/etc/resolv.conf' moved."
  fi

  touch "${TARGET}/etc/resolv.conf"
  chmod 0644 "${TARGET}/etc/resolv.conf"

  ### Create '/etc/resolv.conf' IPv4 entries for static configuration.
  if [[ "${network_autoconfig_enable,,}" == "false" ]]; then
    cat << EOF >> "${TARGET}/etc/resolv.conf"
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.installer
# SPDX-Security-Contact: security@coresecret.eu

# Custom DNS IPv4 configuration
EOF

    for ns in "${ary_ipv4_ns[@]}"; do
      echo "nameserver ${ns}" >> "${TARGET}/etc/resolv.conf"
    done

    echo "" >> "${TARGET}/etc/resolv.conf"
    do_log "info" "false" "IPv4 nameserver at: '${TARGET}/etc/resolv.conf' configured manually."

  fi

  ### Create '/etc/resolv.conf' IPv6 entries for static configuration.
  if [[ "${network_autoconfig_enable,,}" == "false" && -n "${network_static_ipv6address}" ]]; then

    cat << EOF >> "${TARGET}/etc/resolv.conf"
# Custom DNS IPv6 configuration
EOF

    for ns in "${ary_ipv6_ns[@]}"; do
      echo "nameserver ${ns}" >> "${TARGET}/etc/resolv.conf"
    done

    echo "" >> "${TARGET}/etc/resolv.conf"
    do_log "info" "false" "IPv6 nameserver at: '${TARGET}/etc/resolv.conf' configured manually."

  fi

  cat << EOF >> "${TARGET}/etc/resolv.conf"
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
EOF

  ### Ensure Internet Systems Consortium DHCP Client is not overwriting the static nameserver settings.
  if [[ -f "${TARGET}/etc/dhcp/dhclient.conf" ]]; then
    mkdir -p "${DIR_BAK}/etc/dhcp"
    cp "${TARGET}/etc/dhcp/dhclient.conf" "${DIR_BAK}/etc/dhcp/dhclient.conf.bak"
    do_log "info" "false" "Existing '${TARGET}/etc/dhcp/dhclient.conf' saved."
  fi

  if [[ "${network_autoconfig_enable,,}" == "true" && -n "${network_static_ipv4nameserver_0}" ]]; then

    cat << EOF >> "${TARGET}/etc/dhcp/dhclient.conf"

# Custom dhclient config to override DHCP DNS
EOF
    declare var_supersede; var_supersede=$(printf "%s, " "${ary_ipv4_ns[@]}")
    var_supersede="${var_supersede%, }"
    echo "supersede domain-name-servers ${var_supersede};" >> "${TARGET}/etc/dhcp/dhclient.conf"

    do_log "info" "false" "DHCP client configuration for IPv4: '${TARGET}/etc/dhcp/dhclient.conf' configured."

  fi

  if [[ "${network_autoconfig_enable,,}" == "false" && -n "${network_static_ipv6nameserver_0}" ]]; then

    declare var_supersede_ipv6; var_supersede_ipv6=$(printf "%s, " "${ary_ipv6_ns[@]}")
    var_supersede_ipv6="${var_supersede_ipv6%, }"
    echo "supersede domain-name-servers ${var_supersede_ipv6};" >> "${TARGET}/etc/dhcp/dhclient.conf"

    do_log "info" "false" "DHCP client configuration for IPv6: '${TARGET}/etc/dhcp/dhclient.conf' configured."

  fi

  if [[ "${network_autoconfig_enable,,}" == "true" && -n "${network_static_ipv4nameserver_0}" ]]; then

    cat << EOF >> "${TARGET}/etc/dhcp/dhclient.conf"

# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
EOF
  fi

  ### Export hostname and IPv4 and IPv6 addresses for further processing according to dynamic results and preseed.yaml settings.
  if [[ "${network_autoconfig_enable,,}" == "true" ]]; then

    declare -grx VAR_FINAL_NIC="${var_auto_nic}"
    declare -grx VAR_FINAL_FQDN="${var_auto_fqdn}"
    declare -grx VAR_FINAL_IPV4="${var_auto_ipv4}"
    declare -grx VAR_FINAL_IPV4_GW="${var_auto_ipv4_gw}"
    declare -grx VAR_FINAL_IPV4_SUBNET="${var_auto_ipv4_subnet}"

  else

    declare -grx VAR_FINAL_NIC="${network_choose_interface_static}"
    declare -grx VAR_FINAL_FQDN="${network_hostname}"
    declare -grx VAR_FINAL_IPV4="${network_static_ipv4address}"
    declare -grx VAR_FINAL_IPV4_GW="${network_static_ipv4gateway}"
    declare -grx VAR_FINAL_IPV4_SUBNET="${network_static_ipv4netmask}"

  fi

  if [[ "${network_autoconfig_enable,,}" == "true" && "${var_link_ipv6,,}" == "true" ]]; then

    declare -grx VAR_FINAL_IPV6="${var_auto_ipv6}"
    declare -grx VAR_LINK_IPV6="${var_link_ipv6}"

  elif [[ "${network_autoconfig_enable,,}" == "false" && -n "${network_static_ipv6address}" ]]; then

    declare -grx VAR_FINAL_IPV6="${network_static_ipv6address}"

  else

    declare -grx VAR_FINAL_IPV6=""

  fi

  return 0
}
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
