#!/bin/bash
# Copyright (C) 2004 Networks Associates Technology Inc. All rights reserved.

shopt -s extglob	# extended globs rule
shopt -s dotglob	# no hiding place
shopt -s nullglob	# no match no token
umask 022		# reasonable umask

# cd to the directory where this script lives
me=${0##*/}
mydir=${0%$me}
[[ -n $mydir ]] && cd "$mydir" || exit

# hotfix name should be the name of this directory
hf=${PWD##*/}

. /var/NAIENV/.profile.vars
PATH=$wsPATH:$PATH
export LC_ALL=C

# constants
hf_logs=/logs/hotfixes
hf_dir=$NETAWSS/hotfixes
hf_about=$hf_dir/about

# output to log file
mkdir -p $hf_logs
exec >>$hf_logs/hotfixlog 2>&1 </dev/null
echo -e "\n------- Start $(date)"

# function for progress output
ReportMessage() { :; }	# no-op by default, but source from file if possible...
if [[ -f message_functions.bash ]] && . message_functions.bash; then :
else
    [[ -f $WS_MGMT/message_functions.bash ]] &&
	. $WS_MGMT/message_functions.bash
fi

###############################################################################
# Check for prerequisites
###############################################################################
missing=''
[[ -s prerequisites ]] && for f in $(<prerequisites); do
    x=( $hf_about/$f-+([^.-]).+([^.-]) )
    [[ ${#x[@]} -gt 0 ]] || missing="$missing $f"
done
if [[ -n $missing ]]; then
    echo $'\n---------------------------------------------------------'
    echo "Hotfix $hf $(date) missing prerequisites$missing"
    ReportMessage MSG_prerequisite "${missing# }"
    sleep 10
    exit 1
fi

###############################################################################
# Start for real
###############################################################################

echo $'\n---------------------------------------------------------'
echo "Installing Hotfix $hf $(date)"
ReportMessage MSG_install_hotfix "$hf"

# self check
if (
	cd .. && [[ -d validate ]] || exit 0
	echo "Self-check hotfix content"
	if [[ -f validate/filelist.txt ]]; then
	    m=$(find * -type f -print | sort | comm -3 validate/filelist.txt -)
	    [[ -n $m ]] && echo -e "File list mismatch:\n$m" && exit 1
	fi
	if [[ -f validate/md5sum.txt ]]; then
	    md5sum -c validate/md5sum.txt || exit 1
	fi
    ); then :
else
    echo "Self-check FAILED!"
    ReportMessage MSG_hotfix_failed "$hf"
    sleep 5
    exit 1
fi

# remove the cron file
rm -f /etc/cron.d/spam_uricf_upd.cron

# update about box
echo "Updating about box"
mkdir -p $hf_about && :> $hf_about/$hf
$WSMGMT/abouthotfixes

# all done
echo -e "\nCompleted Hotfix $hf $(date)"

# report completion and exit
if [[ -e reboot_ui && $(<reboot_ui) != *nohttpd* ]]; then
    # have to restart apache, so bg it with a sleep and exit before it happens
    ReportMessage MSG_ui_restart 15
    exec 3>&-
    ( cd /; sleep 15; until /etc/init.d/httpd restart; do sleep 5; done ) &
else
    ReportMessage MSG_hotfix_success "$hf"
fi
sleep 5
exit
