#!/bin/bash
#
# post_install (c) phion AG 2001-2010
#

# /etc/phion/bin/post_install call path:
#	1) ks.sh (anaconda):	without option in case of rescue
#							with "part1" for auto installation
#	2) autoinstallation_stick (gconf)
#							with "part2"
#	3) update pkg			with "part2"
#	4) nginstall			withouth option

#
# /etc/phion/bin/post_install tasks:
#	1) part1: 	* install additional stuf
#				* write default booloader.conf
#				* fix inittab
#	2) part2:	* write bootloader.conf
#	3) without option: part1 and part2


# $1: path to package repository
function get_list_of_64bit_rpms()
{
	RPMLIST=""
	SRC=${1}
	for n in $(ls ${SRC}/*.x86_64.rpm); do
		RPMNAME=$(rpm -q --qf '%{name}' -p ${n})
		rpm -q ${RPMNAME} 2>&1 >/dev/null
		if [ $? -eq 0 ]; then
			RPMLIST="${RPMLIST} ${n}"
		#else
		#	echo "NOT ADDING ${n}"
		fi
	done
	echo "${RPMLIST}"
}

function install_add_stuff()
{
	DEV=$(cat /proc/mounts|grep stage2|awk '{print $1}')
	if [ -z "$DEV" ]; then
		# usb stick installation
		DEV=$(cat /proc/mounts|grep phionusbstick|awk '{print $1}')
		if [ -z "$DEV" ]; then
			# recovery installation
			BUSYBOX=/usr/lib/mkinitrd/busybox_ks
			if [ -x ${BUSYBOX} ]; then
				DEV=$(${BUSYBOX} findfs LABEL=/art)
			fi
		fi

		[ -z "$DEV" ] && return 1

		mkdir /mnt/_cdrom
		mount ${DEV} /mnt/_cdrom
		ISO=$(ls /mnt/_cdrom/*.iso)
		if [ ! -z "${ISO}" ]; then
			if [ "$1" = "x86_64" ]; then
				mkdir /mnt/_source
				mount ${ISO} /mnt/_source -o loop
				RPMLIST=$(get_list_of_64bit_rpms /mnt/_source/Packages/)
				rpm -Uvh --ignorearch --force ${RPMLIST}
				umount /mnt/_source
				rmdir /mnt/_source
			fi
			[ -d /art -a ${SKIPISO} -ne 1 ] && cp ${ISO} /art/netfence.iso
		fi
		umount /mnt/_cdrom
		rmdir /mnt/_cdrom
	else
		# cdrom installation
		if [ "$1" = "x86_64" ]; then
			mkdir /mnt/_cdrom
			mount ${DEV} /mnt/_cdrom
			RPMLIST=$(get_list_of_64bit_rpms /mnt/_cdrom/Packages/)
			rpm -Uvh --ignorearch --force ${RPMLIST}

			umount ${DEV}
			rmdir /mnt/_cdrom
		fi
		[ -d /art -a ${SKIPISO} -ne 1 ] && /bin/dd if=${DEV} of=/art/netfence.iso 
	fi

	if [ "$1" = "x86_64" ]; then
		VERSION=$(uname -r)
		VERSION=${VERSION%.*}
		ARCH=i686
		if [ ! -f /boot/vmlinuz-${VERSION}.${ARCH} ]; then
			# in anaconda context, the running kernel could differ from the installed kernel
			# (different NGinstall), so uname -r could not be appropriate
			# so, lets check for the i686 version of the installed kernel
			VERSION=$(rpm -q --qf "%{version}-%{release}" kernel)
		fi

		/sbin/new-kernel-pkg --rminitrd --rmmoddep --remove ${VERSION}.${ARCH}
		rm /boot/System.map-${VERSION}.${ARCH}
		rm /boot/config-${VERSION}.${ARCH}
		rm /boot/vmlinuz-${VERSION}.${ARCH}
		# remove kernel modules
		rm -rf /lib/modules/${VERSION}.${ARCH}
	fi
}

PATH="/sbin:/bin:/usr/sbin:/usr/bin:/etc/phion/bin:/opt/phion/bin"

AUTOINSTALLATION="" 
SKIPISO=0

# parameter handling
i=1
PARAM=$1
while [ ! -z "${PARAM}" ]; do
	eval PARAM=\${${i}}
	[ "${PARAM}" = "--skipiso" ] && SKIPISO=1
    [ "${PARAM}" = "--autoinstallation" ] && {
		eval PARAM=\${$((${i}+1))}
		AUTOINSTALLATION=${PARAM}
	}
	let i=$i+1
done

# Removed by MPR see log #5187
# [ -x /usr/sbin/usernetctl ] && chmod u-s /usr/sbin/usernetctl


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

if [ -f /etc/phion/phion.sh ]; then
	chmod 0755 /etc/phion/phion.sh
        ln -sf /etc/phion/phion.sh /etc/profile.d/phion.sh
	. /etc/phion/phion.sh
fi

if [ -f /etc/phion/rc.d/phion ]; then
	chmod 0755 /etc/phion/rc.d/phion
        ln -sf /etc/phion/rc.d/phion /etc/init.d/phion
fi

if [ -f /etc/phion/rc.d/inet ]; then
	chmod 0755 /etc/phion/rc.d/inet
        ln -sf /etc/phion/rc.d/inet /etc/init.d/inet
fi

if [ ! -L /bin/rbash ]; then
	ln -sf /bin/bash /bin/rbash
fi

# Remove network configuration done by anaconda
rm -f /etc/sysconfig/network-scripts/ifcfg*
rm -f /etc/udev/rules.d/70-persistent-net.rules

# BNNGF-48468: remove phion service user completely 
# useradd -u 9999 phion

###################################
#
# Implement correct boot sequences
#
###################################

STOPMODULES=("squid" "sshd" "ntpd")
#STARTMODULES=("phion" "phiondeferred" "irqbalance")

for n in ${STOPMODULES[@]}; do
	systemctl disable $n
done

#for n in ${STARTMODULES[@]}; do
#	systemctl enable $n
#	systemctl add-wants multi-user.target $n
#done

# Watchdog activate now takes care of smartd. Default state is off.
chkconfig smartd off

###################################
#
# install x86_64 kernel
#
###################################
if [ "$AUTOINSTALLATION" = "part1"  -o -z "$AUTOINSTALLATION" ]; then
	if [ $(cat /proc/cpuinfo | grep "^flags" | grep -cw "lm") -gt 0 -a ! -f /etc/phion/install32bit ]; then
		install_add_stuff x86_64
	else
		install_add_stuff
	fi

	# fix default runlevel. its set to 3 by anaconda
	cat /etc/inittab |sed "s/id:3/id:2/" > /etc/inittab.tmp; [ -s /etc/inittab.tmp ] && mv -f /etc/inittab.tmp /etc/inittab
fi

if [ "$AUTOINSTALLATION" = "part2"  -o -z "$AUTOINSTALLATION" ]; then
	# trigger buildarttree (in rc.sysinit) in next boot
	touch /opt/phion/preserve/FIRSTBOOT
fi


###################################
#
# system config changes
#
###################################
echo "MAKEWHATISDBUPDATES     n" >> /etc/man.config

if [ "$AUTOINSTALLATION" = "part1" ]; then
	# do not turn on serial console in first boot on VMwares
	ISVM=$(/opt/phion/bin/hwtool -m 2>/dev/null)
	INITIALSERIALOPT=0
 
	# some appliance model won't reboot without ACPI (e.g. F12)
	if [[ $ISVM == F12 ]] || [[ $ISVM == F18b ]] || [[ $ISVM == F80b ]]; then
		ACPIPARAM=''
	else
		ACPIPARAM='NOACPI = y'
	fi

	cat > /tmp/bootloader.conf << EOF
SERIAL = ${INITIALSERIALOPT}
${ACPIPARAM}
APPEND = nosmp
EOF

	/etc/phion/bin/mergeconf  /opt/phion/modules/box/boxother/bootloader/default.conf /tmp/bootloader.conf /opt/phion/config/active/bootloader.conf
	rm -f /tmp/bootloader.conf

elif [ "$AUTOINSTALLATION" = "part2" ]; then
	rm -f /opt/phion/config/configroot/boxother/bootloader.conf
fi

if [ -e /opt/phion/update/box.par ]; then

	TIME=$(/bin/date +%s)	
	mkdir /tmp/${TIME}
	cd /tmp/${TIME}
	/opt/phion/bin/phionar x /opt/phion/update/box.par 	 
	cp -f ./boxother/bootloader.conf /opt/phion/config/active/bootloader.conf  &>/dev/null
	cd -
	rm -rf /tmp/${TIME}

elif [ -e /opt/phion/update/box.pgz ]; then

	TIME=$(/bin/date +%s)	
	mkdir /tmp/${TIME}
	cd /tmp/${TIME}
	gunzip -cf /opt/phion/update/box.pgz > /opt/phion/update/box.par
	/opt/phion/bin/phionar x /opt/phion/update/box.par 	 
	cp -f ./boxother/bootloader.conf /opt/phion/config/active/bootloader.conf  &>/dev/null
	rm /opt/phion/update/box.par
	cd -
	rm -rf /tmp/${TIME}
	
elif [ -e /opt/phion/config/active/bootloader.conf ]; then
	/etc/phion/bin/mergeconf  /opt/phion/modules/box/boxother/bootloader/default.conf /opt/phion/config/active/bootloader.conf /opt/phion/config/active/bootloader.conf.1
	/bin/mv -f /opt/phion/config/active/bootloader.conf.1 /opt/phion/config/active/bootloader.conf 
fi

if [ -e /opt/phion/config/active/bootloader.conf ]; then
	/etc/phion/bin/activatebbloader -H /opt/phion/config/active/bootloader.conf
elif [ -e /opt/phion/config/configroot/boxother/bootloader.conf ]; then
	# this should never occur!!!
	/etc/phion/bin/activatebbloader -H /opt/phion/config/configroot/boxother/bootloader.conf
elif [ -e /opt/phion/modules/box/boxother/bootloader/default.conf ]; then
	 /etc/phion/bin/activatebbloader -H /opt/phion/modules/box/boxother/bootloader/default.conf
fi

# remove old, by anaconda generated initramfs on hardware due to BNNGF-56034
for f in /boot/initramfs-[0-9]*\.[0-9]*\.[0-9]*-ph[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\.x86\_64\.img; do
	out=$(rpm -qf $f)
	if [[ $? != 0 ]]; then
		$(rm $f)
		echo "removed initramfs $f"
	fi
done

# when doing rescue installation, delete old kernel and initramfs
# ONLY applicable when doing ART installation, otherwise kernel may differ
for i in $(cat /proc/cmdline); do
	if [[ "$i" = "art" ]]; then
		for i in $(ls /boot/vmlinuz-*); do
			if [ "$i" = "/boot/vmlinuz-0-rescue-$(cat /etc/machine-id)" -o "$i" = "/boot/vmlinuz-$(uname -r)" ]; then
				# do NOT delete new kernel
				continue
			fi
			rm $i
		done
		
		for i in $(ls /boot/initramfs-*); do
			if [ "$i" = "/boot/initramfs-0-rescue-$(cat /etc/machine-id).img" -o "$i" = "/boot/initramfs-$(uname -r).img" ]; then
				# do NOT delete new initramfs
				continue
			fi
			rm $i
		done
		grub2-mkconfig -o /boot/grub2/grub.cfg
	fi
done

