#!/bin/bash
#
# recordum_dhclient_fix
#
# v0.1 2019-05-13 RE
#
# add hostname to the dhcp client request

MYSELF=$( basename $0 )

# get our ID
# serial
SERIAL=$( /usr/local/recordum/dataproc/getserial 2>/dev/null )
# product
PRODUCT=$( cat /usr/local/recordum/PRODUCT_CODE )
if [[ -z "$PRODUCT" || ${SERIAL} == "UNKNOWN" ]]
then
    echo "$MYSELF unable to identify product or serial"
    exit 1
fi

SERIAL_LC=$( echo ${SERIAL} | tr [A-Z] [a-z] )
PRODUCT_LC=$( echo ${PRODUCT} | tr [A-Z] [a-z] )
HOST_NAME="${PRODUCT_LC}-${SERIAL_LC}"

# helper
script_help() {
    cat <<EOF
${MYSELF} help:

This script adds the hostname to the dpcp client configuration. It needs root privileges!

Usage: ${MYSELF}

EOF
}

if [[ $UID -gt 0 ]]
then
    echo "$MYSELF needs to be run as superuser. You are $USER."
    script_help
    exit 2
fi

if [[ -f /etc/dhcp/dhclient.conf ]]
then
    cat > /tmp/101.fix_dhclient.cf <<EOF
#!/usr/sbin/cfagent -f

control:
    any::
        actionsequence = ( editfiles )
        EditFileSize = (30000 )

editfiles:
    any::        
        { /etc/dhcp/dhclient.conf
            LocateLineMatching ".*send host-name.*"
            ReplaceLineWith "send host-name \"${HOST_NAME}\";"
        }
        
EOF
    echo "add/fix hostname to/in dhclient.conf"
    /usr/sbin/cfagent -KIf /tmp/101.fix_dhclient.cf
fi

exit 0
