#!/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

read HOSTNAME < /proc/sys/kernel/hostname
if [ "${HOSTNAME}" = "(none)" ]; then
    HOSTNAME_BASE="ltsp"
    # get networking configuration
    . /tmp/net-*.conf
    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
    # if HOSTNAME was not defined in lts.conf,
    # or if it has been nulled by /tmp/net-*.conf
    if [ "$HOSTNAME" = "(none)" ] || [ -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
