#!/bin/bash
#
# recordum_hostname
#
# v0.1 2014-10-24 RE
#
# script changes hostname in various places

MYSELF=$( basename $0 )
NOW=$( date +%Y.%m.%d.%H.%M )

MY_IP=$( ip -4 addr show eth0 |grep global |awk '{print $2}' |cut -d "/" -f 1 |awk 'FNR <= 1' )
if [[ -z "$MY_IP" ]]; then
    MY_IP=172.19.3.37
fi
MY_NET=$( echo ${MY_IP} |cut -d '.' -f 1-2 )

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

This script sets hostname for system and postfix. It needs root privileges!

Usage: ${MYSELF} <HOSTNAME> [ <DOMAIN> ]

where:
    HOSTNAME ... the local part of the FQDN
    DOMAIN ... the rest of it

EOF
}

if [[ $# -lt 1 || $# -gt 2 ]]
then
    echo "incorrect number of command line parameters!"
    script_help
    exit 1
fi
if [[ $UID -gt 0 ]]
then
    echo "$MYSELF needs to be run as superuser. You are $USER."
    script_help
    exit 2
fi

HOST_NAME=$1
DOMAIN=$2
if [[ -n "$DOMAIN" ]]
then
    FQDN="${HOST_NAME}.$DOMAIN"
else
    FQDN=${HOST_NAME}
fi
echo "${HOST_NAME}" > /etc/hostname
echo "${HOST_NAME}" > /etc/mailname

cat > /tmp/000.fix_hostname.cf <<EOF
#!/usr/sbin/cfagent -f

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

editfiles:
    any::
        { /etc/postfix/main.cf
            LocateLineMatching "myhostname.*"
            ReplaceLineWith "myhostname = ${FQDN}"
        }
        
        # first try to replace settings
        { /etc/hosts
            LocateLineMatching "${MY_NET}.*"
            ReplaceLineWith "${MY_IP} ${FQDN} ${HOST_NAME}"
        }
        # then append them if still missing
        { /etc/hosts
            SetLine "${MY_IP} ${FQDN} ${HOST_NAME}"
            AppendIfNoLineMatching "${MY_NET}.*"
        }
        
        { /etc/dhcp/dhclient.conf
            LocateLineMatching ".*send host-name.*"
            ReplaceLineWith "send host-name \"${HOST_NAME}\";"
        }
        
EOF
echo "fix postfix/main.cf and hosts"
/usr/sbin/cfagent -KIf /tmp/000.fix_hostname.cf

# now change the hostname
hostname $( cat /etc/hostname )
service postfix restart

exit 0
