#! /usr/bin/env bash


#Preupgrade assistant performs system upgradability assessment
#and gathers information required for successful operating system upgrade.
#Copyright (C) 2013 Red Hat Inc.
#Boris Ranto <branto@redhat.com>
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
. /usr/share/preupgrade/common.sh
check_applies_to "krb5-server"
COMPONENT="krb5-server"
#END GENERATED SECTION

# This check can be used if you need root privilegues
check_root

KRB_SYSCONFIG_FILE=/etc/sysconfig/krb5kdc

KRB5REALM=""

if ! test -s "$KRB_SYSCONFIG_FILE"; then
	# Nothing to modify
	exit "$RESULT_NOT_APPLICABLE"
fi

if ! grep -q "KRB5REALM" "$KRB_SYSCONFIG_FILE"; then
	# Nothing to do, no KRB5REALM in the config file
	exit "$RESULT_NOT_APPLICABLE"
fi

# Otherwise, fix the config

# Backup the file, first
#FIXME: this is incorrect way, in fact, postupgrade script is not necessary and the modified file should be placed in cleanconf (config files in cleanconf are migrated automatically by generic postupgrade script)
#mkdir -p "$VALUE_TMP_PREUPGRADE/cleanconf/$(dirname $KRB_SYSCONFIG_FILE)/"
#cp --parents -a "$KRB_SYSCONFIG_FILE" "$VALUE_TMP_PREUPGRADE/cleanconf/"

# Create the directory structure
TARGET_DIR="$POSTUPGRADE_DIR/system/"
TARGET_SCRIPT_NAME="$TARGET_DIR/01-krbMigration.sh"

mkdir -p "$TARGET_DIR"

# Remove the variables from the config file (keeping things like comments intact)
grep -v -e KRB5KDC_ARGS\= -e KRB5REALM\= "$KRB_SYSCONFIG_FILE" > "$TARGET_DIR/krb5kdc"

# The file exists for sure at this moment and this is the simplest way to get the values of KRB5REALM and KRB5KDC_ARGS
. "$KRB_SYSCONFIG_FILE"

# Convert KRB5REALM to KRB5KDC_ARGS if it is of non-zero length
if test -n "$KRB5REALM"; then
	KRB5KDC_ARGS="-r $KRB5REALM $KRB5KDC_ARGS"
fi

# write out the new modified config option
echo "KRB5KDC_ARGS=\"$KRB5KDC_ARGS\"" >> "$TARGET_DIR/krb5kdc"

# copy && +x the postupgrade script
cp postupgrade.d/krbMigration.sh "$TARGET_SCRIPT_NAME"
chmod a+x "$TARGET_SCRIPT_NAME"

# log risk and exit
log_none_risk "The config file /etc/sysconfig/krb5kdc has been converted for use in Red Hat Enterprise Linux 7."
exit "$RESULT_FIXED"
