#!/bin/sh
#
# Copyright (c) 1999-2008 Parallels
# All rights reserved
#

#
# Plesk script
#

HOSTNAME=$1

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.
#
/opt/psa/admin/sbin/hostname-helper --check-name-unused "$HOSTNAME"

if [ "x$?" == "x0" ]; then
    echo "$HOSTNAME" >> /var/qmail/control/locals
fi
