#!/bin/sh

case $1 in
prereqs)
    # We have no prerequisites.
    exit 0
    ;;
esac

# Gracefully exit if ltsp_chroot file is not present
test -f ${rootmnt}/etc/ltsp_chroot || exit 0

# mount writeable filesystems if / is not already mounted writeable.
ltsp_bindmounts=/usr/share/ltsp/ltsp-bindmounts
if ! chroot ${rootmnt} /usr/bin/test -w "/" ; then
    if [ -x ${rootmnt}/${ltsp_bindmounts} ]; then
        chroot ${rootmnt} ${ltsp_bindmounts}
    fi
fi

# set hostname to ltsp if none is received from dhcp

# get networking configuration
. /tmp/net-*.conf

# set to defaults from DHCP if not specified in lts.conf
if [ -z "$DNS_SERVER" ]; then
    for dns in $IPV4DNS0 $IPV4DNS1 ; do
        # ignore nameserver of 0.0.0.0, which ipconfig may return if both
        # nameservers aren't specified.
        if [ "$dns" != "0.0.0.0" ]; then
            DNS_SERVER="$DNS_SERVER $dns"
        fi
    done
fi

if [ -z "$SEARCH_DOMAIN" ] && [ -n "$DNSDOMAIN" ]; then
    SEARCH_DOMAIN="$DNSDOMAIN"
fi

if [ -f ${rootmnt}/etc/lts.conf ] && [ -x ${rootmnt}/usr/bin/getltscfg ]; then
    # get defaults from lts.conf
    eval $(chroot ${rootmnt} /usr/bin/getltscfg -a)
fi

# check if hostname is set
read TEMP_HOSTNAME < /proc/sys/kernel/hostname
if [ "${TEMP_HOSTNAME}" = "(none)" ]; then
    HOSTNAME_BASE=${HOSTNAME_BASE:-ltsp}
    # if HOSTNAME was not defined in lts.conf,
    # or if it has been nulled by /tmp/net-*.conf
    if [ -z "$HOSTNAME" ]; then
        case "$HOSTNAME_EXTRA" in
            mac)
                HOSTNAME_EXTRA=$(ip link show $DEVICE | awk '/ether/{print $2}' | tr ':' '-')
                ;;
            ip|"")
                HOSTNAME_EXTRA=$(echo "$IPV4ADDR.$IPV4NETMASK" | awk -F "." '{ print (($1%(256-$5)*256+$2%(256-$6))*256+$3%(256-$7))*256+$4%(256-$8) }')
                ;;
        esac
        HOSTNAME="$HOSTNAME_BASE$HOSTNAME_EXTRA"
    fi
    echo "$HOSTNAME" > /proc/sys/kernel/hostname
fi
cat /proc/sys/kernel/hostname > ${rootmnt}/etc/hostname || true

# Apply the dns info that was received from dhcp or from lts.conf
# $rootmnt/etc/resolv.conf might be overwritten later on by ltsp-init-common
if [ -n "$DNS_SERVER" ] || [ -n "$SEARCH_DOMAIN" ]; then
    # Check if $rootmnt/etc/resolv.conf is writable
    if echo '# Generated by ltsp' 2>/dev/null > "$rootmnt/etc/resolv.conf"; then
        if [ -n "$SEARCH_DOMAIN" ]; then
            echo "search $SEARCH_DOMAIN" >> "$rootmnt/etc/resolv.conf"
        fi
        for n in $DNS_SERVER; do
            echo "nameserver $n" >> "$rootmnt/etc/resolv.conf"
        done
    fi
fi
