Files
debian-unattended/postinstall/init.sh

92 lines
2.6 KiB
Bash

#!/usr/bin/env bash
# Get the current DHCP network address, gateway and DNS servers. DHCP can
# still be completing when this service starts, even after network-online.
get_network_settings() {
local cidr_address
# Clear every value before each attempt so a partial/stale DHCP lease can
# never be written to the static network configuration.
NIC=""
IP_ADDRESS=""
NETMASK=""
GATEWAY=""
DNS_SERVERS=""
NIC=$(ip link | awk -F ': ' '$1 == 2 {sub(/@.*/, "", $2); print $2; exit}')
[ -n "${NIC}" ] || return 1
cidr_address=$(ip -4 address show "${NIC}" | awk '/inet / {print $2; exit}')
[ -n "${cidr_address}" ] || return 1
IP_ADDRESS=${cidr_address%/*}
NETMASK=${cidr_address#*/}
GATEWAY=$(ip route show default | awk 'NR == 1 {print $3}')
DNS_SERVERS=$(awk '/^nameserver/ {print $2}' /etc/resolv.conf | xargs)
[ -n "${IP_ADDRESS}" ] && [ -n "${NETMASK}" ] && \
[ -n "${GATEWAY}" ] && [ -n "${DNS_SERVERS}" ]
}
MAX_NETWORK_ATTEMPTS=10
for attempt in $(seq 1 "${MAX_NETWORK_ATTEMPTS}"); do
if get_network_settings; then
break
fi
if [ "${attempt}" -eq "${MAX_NETWORK_ATTEMPTS}" ]; then
echo "DHCP network settings were incomplete after ${MAX_NETWORK_ATTEMPTS} attempts; aborting postinstall." >&2
exit 1
fi
echo "DHCP network settings are not ready (attempt ${attempt}/${MAX_NETWORK_ATTEMPTS}); retrying in 3 seconds." >&2
sleep 3
done
# Tear down DHCP first, while interfaces is still dhcp, so dhcpcd is gone
# before we write a static resolv.conf (otherwise it rewrites it on exit)
ifdown "${NIC}" || true
# Network interfaces (static address)
cat << EOF > /etc/network/interfaces
auto lo
iface lo inet loopback
auto ${NIC}
iface ${NIC} inet static
address ${IP_ADDRESS}/${NETMASK}
gateway ${GATEWAY}
dns-nameservers ${DNS_SERVERS}
EOF
# Tabs instead of spaces, neat the file
sed -i 's/ /\t/gm' /etc/network/interfaces
ifup "${NIC}" || true
# write a static resolv.conf after dhcpcd is gone so it survives reboot
rm -f /etc/resolv.conf
for ns in ${DNS_SERVERS}; do
echo "nameserver ${ns}" >> /etc/resolv.conf
done
# Hosts file
cat << EOF > /etc/hosts
127.0.0.1 localhost localhost.localdomain
::1 localhost localhost.localdomain
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
${IP_ADDRESS} $(hostname --fqdn) $(hostname)
EOF
# Tabs instead of spaces, neat the file
sed -i 's/ /\t/gm' /etc/hosts
# Personalizations
wget -O - https://45r.it/serversetup | bash
# Cleanup and reboot
rm -rf /etc/systemd/system/multi-user.target.wants/postinstall-init.service /var/lib/systemd/system/postinstall-init.service /debian-postinstall-init.sh /.wget-hsts
reboot