#!/bin/bash
### Copyright 1999-2015. Parallels IP Holdings GmbH. All Rights Reserved.
#

#
# Plesk script
#


### Copyright 1999-2015. Parallels IP Holdings GmbH. All Rights Reserved.


### Copyright 1999-2015. Parallels IP Holdings GmbH. All Rights Reserved.
HOSTNAME=$1

OLD_HOSTNAME="`cat /var/qmail/control/me`"
echo "$HOSTNAME" > /var/qmail/control/me

#
# Exclude last hostname from qmail/control/locals which is not a predefined
# record.
#
sed -i '
    /^localhost\(\.localdomain\)\?$/ {

        # Flush the content of the hold buffer and pass the current record.

        # Exchange content of the hold buffer and current record
        x

        # If pattern taken from hold buffer is not empty - print it.
        /./ p
        
        # Erase the pattern in such a way to not start next cycle.
        s/.*//g
        
        # Put the original content back from hold buffer to current pattern.
        x

        # Pass predefined localhost records to stdout.
        b
    }

    /^$/ {
        # Prune empty lines.
        d
        b
    }

    # Remember the current not empty line, assuming it is a hostname.
    # Previously remembered line now becomes current.
    x

    /./ {
        # Print the current line if it is not empty.
        p
    }

    # Do not output anything what was not explicitly printed before.
    d
' /var/qmail/control/locals

#
# Put the new hostname into locals, if it not coincides with domains having
# their own mail systems.
#
/usr/local/psa/admin/sbin/hostname-helper --check-name-unused "$HOSTNAME"

if [ $? -eq 0 ]; then
    echo "$HOSTNAME" >> /var/qmail/control/locals
fi

#
# Replace old hostname with new one in rcpthosts
#
if [ -n "$OLD_HOSTNAME" ]; then
    escaped_old_hostname=`echo $OLD_HOSTNAME | sed 's/[][\.*^$/]/\\\&/g'`
    sed -i 's/^'$escaped_old_hostname'$/'$HOSTNAME'/g' /var/qmail/control/rcpthosts
fi
