#!/bin/bash
#
# Copyright (c) 2010--2015 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

if [ 0$UID -gt 0 ]; then
    echo "$0 has to be run as root."
    exit 1
fi

RHN_CONF_FILE=/etc/rhn/rhn.conf
SSL_BUILD_DIR=/root/ssl-build
HTTP_PUB_DIR=/srv/www/htdocs/pub/
BOOTSTRAP_SH=/srv/www/htdocs/pub/bootstrap/bootstrap.sh
BOOTSTRAP_CCO=/srv/www/htdocs/pub/bootstrap/client-config-overrides.txt
MGR_SYNC_CONF=/root/.mgr-sync
BACKUP_EXT=.rnmbck
CA_CERT_TRUST_DIR=/etc/pki/trust/anchors/

###############################################################################

function echo_err {
    echo "$*" >&2
}

function bye {
    echo_err "Fix the problem and run $0 again"
    exit 1
}

function print_status {
    # strip whitespace
    STATUS="${1#"${1%%[![:space:]]*}"}"
    if [ "$STATUS" == "0" ]
    then
        echo "OK"
    else
        echo_err "FAILED"
        shift
        echo_err $*
        bye
    fi
}

function initial_system_hostname_check {
    # check for uppercase chars in hostname
    if [ "$UYUNI_HOSTNAME" != "$(echo $UYUNI_HOSTNAME | tr '[:upper:]' '[:lower:]')" ]
    then
        echo_err "Uppercase characters are not allowed for the hostname."
        return 1
    fi

    return 0
}

function backup_file {
    if [ -e ${1} ]
    then
        cp ${1} ${1}${BACKUP_EXT}
    else
        echo_err "Backup of ${1} failed. File not found."
    fi
}

function update_rhn_conf {
    sed "s/^cobbler\.host[[:space:]]*=[[:space:]]*.*$/cobbler.host = localhost/" -i /etc/rhn/rhn.conf
    sed "s/^java\.hostname[[:space:]]*=[[:space:]]*.*$/java.hostname = ${UYUNI_HOSTNAME}/" -i /etc/rhn/rhn.conf
}

function update_server_ssl_certificate {
    /usr/sbin/update-ca-certificates
    /usr/bin/rhn-ssl-dbstore --ca-cert /etc/pki/trust/anchors/LOCAL-RHN-ORG-TRUSTED-SSL-CERT
    /usr/sbin/mgr-package-rpm-certificate-osimage
}

###############################################################################

# This awk command can read a single line yaml value which may optionally be double or single quoted.
OLD_HOSTNAME=$(sed -n '/^java\.hostname/{s/^java\.hostname[[:space:]]*=[[:space:]]*\(.*\)/\1/;p}' "$RHN_CONF_FILE")
if [ -z "$UYUNI_HOSTNAME" -o "z$UYUNI_HOSTNAME" == "z$OLD_HOSTNAME" ]
then
    echo_err "Unchanged hostname or unset UYUNI_HOSTNAME"
    exit 0
fi

echo "============================================="
echo "hostname: $UYUNI_HOSTNAME"
echo "old hostname: $OLD_HOSTNAME"
echo "============================================="

initial_system_hostname_check || bye

backup_file $RHN_CONF_FILE

echo -n "Testing DB connection ... "
/usr/sbin/spacewalk-startup-helper wait-for-database
print_status "${?}" "The database isn't running."

echo -n "Updating /etc/rhn/rhn.conf ... "
update_rhn_conf
print_status 0  # just simulate end

# Make sure the SSL certificate change has been reflected
update_server_ssl_certificate

echo -n "Regenerating new bootstrap client-config-overrides.txt ... "
# it's easier to subst HOSTNAME with sed
# than to re-generate and keep current configuration
if [ -e "$BOOTSTRAP_SH" ]
then
    backup_file ${BOOTSTRAP_SH}
    sed -i "s/\(HOSTNAME=\).*/\1$UYUNI_HOSTNAME/" ${BOOTSTRAP_SH}
fi
if [ -e "$BOOTSTRAP_CCO" ]
then
    backup_file ${BOOTSTRAP_CCO}
    sed -i "s/\(serverURL=https\?:\/\/\).*\(\/XMLRPC\)/\1$UYUNI_HOSTNAME\2/" ${BOOTSTRAP_CCO}
fi
print_status 0  # just simulate end

echo -n "Updating other DB entries ... "
spacewalk-sql --select-mode - <<EOS
UPDATE rhntemplatestring SET value='$UYUNI_HOSTNAME' WHERE label='hostname';
COMMIT;
\q
EOS
print_status 0  # just simulate end

# Update Salt Master configuration
ROSTER_CONF="/etc/salt/master.d/uyuni_roster.conf"
if [ -f "$ROSTER_CONF" ]; then
    echo -n "Updating Salt configuration files ... "
    
    SHORT_OLD_HOSTNAME="${OLD_HOSTNAME%%.*}"
    SHORT_NEW_HOSTNAME="${UYUNI_HOSTNAME%%.*}"
    ESCAPED_OLD_HOSTNAME="${OLD_HOSTNAME//./\\.}"

    if grep -qE "$ESCAPED_OLD_HOSTNAME|\b$SHORT_OLD_HOSTNAME\b" "$ROSTER_CONF"; then
        backup_file "$ROSTER_CONF"
        sed -i -e "s/$ESCAPED_OLD_HOSTNAME/$UYUNI_HOSTNAME/g" \
               -e "s/\b$SHORT_OLD_HOSTNAME\b/$SHORT_NEW_HOSTNAME/g" "$ROSTER_CONF"
    fi
    
    print_status 0
fi

echo -n "Changing cobbler settings ... "
/usr/bin/spacewalk-setup-cobbler --apache2-config-directory "/etc/apache2/conf.d" --fqdn $UYUNI_HOSTNAME 2>&1
print_status $?

echo -n "Changing kernel_options ... "
spacewalk-sql --select-mode - <<EOS
UPDATE rhnKickstartableTree
SET kernel_options = REPLACE(kernel_options, '$OLD_HOSTNAME', '$UYUNI_HOSTNAME'),
    kernel_options_post = REPLACE(kernel_options_post, '$OLD_HOSTNAME', '$UYUNI_HOSTNAME');
COMMIT;
\q
EOS
for COBBLERDIR in /var/lib/cobbler/collections/*
do
    if [ -d $COBBLERDIR ] && [ ! -z "$(ls $COBBLERDIR)" ]; then
        for FILE in $COBBLERDIR/*
        do
            backup_file $FILE
            sed -i "s/$OLD_HOSTNAME/$UYUNI_HOSTNAME/g" $FILE
        done
    fi
done
print_status 0  # just simulate end

# change /root/.mgr-sync
if [ -e $MGR_SYNC_CONF ]; then
    backup_file $MGR_SYNC_CONF
    sed -i "s/^mgrsync.host\s\{0,1\}=\s\{0,1\}.*/mgrsync.host = $UYUNI_HOSTNAME/g" $MGR_SYNC_CONF
    sed -i "s/^mgrsync.session.token\s\{0,1\}=\s\{0,1\}.*/mgrsync.session.token = \"\"/g" $MGR_SYNC_CONF
fi
print_status 0  # just simulate end

# Schedule a pillar refresh of all the minions since they container the repos URLs with the old hostname
spacewalk-sql --select-mode - <<EOS
INSERT INTO rhnTaskQueue (id, org_id, task_name, task_data)
SELECT nextval('rhn_task_queue_id_seq'), id, 'upgrade_satellite_all_systems_pillar_refresh', 0
FROM web_customer
WHERE id = 1;
COMMIT;
\q
EOS

echo -n "Changing postfix settings ... "
postconf -e myhostname=$UYUNI_HOSTNAME

echo "[$(date)]: $(basename $0) finished successfully."
