#!/bin/bash

if [ $(id -u) -ne 0 ]; then
        echo -e "This script needs to be run as root/superuser. Exiting..."
        exit 1
fi

DEVICE="$(df -hkPBG / | tail -1 | awk '{print $1}')"
if [ "$DEVICE" != "/dev/mapper/VolGroup-lv_root" ]; then
        echo "This is not the standard Nagios XI OVA partitioning scheme"
        echo "The script will now exit"
        exit 1
fi

extendfs() {

cat <<'EOF' >> /tmp/extendfs
#!/bin/bash

## Resize filesystem on /dev/sda2
echo "pvresize /dev/sda2" >> /var/log/vm_resize.log
pvresize /dev/sda2 &>> /var/log/vm_resize.log
echo "lvresize /dev/mapper/VolGroup-lv_root /dev/sda2" >> /var/log/vm_resize.log
lvresize /dev/mapper/VolGroup-lv_root /dev/sda2 &>> /var/log/vm_resize.log
echo "resize2fs /dev/mapper/VolGroup-lv_root" >> /var/log/vm_resize.log
resize2fs /dev/mapper/VolGroup-lv_root &>> /var/log/vm_resize.log
echo "/tmp/printsize" >> /root/.bash_profile
sed -i "/\/tmp\/extendfs/d" /usr/local/run.sh
rm $0

EOF
chmod +x /tmp/extendfs
}

printsize() {

cat <<'EOF' >> /tmp/printsize
#!/bin/bash

echo "Your root / partition and filesystem have been resized"

DSIZE="$(echo "pq" | fdisk /dev/sda -l | grep 'Disk /dev/sda' | awk '{print $3}' | tail -n 1)"
UNIT="$(echo "pq" | fdisk /dev/sda -l | grep 'Disk /dev/sda' | awk '{print $4}' | tail -n 1)"
FSSIZE="$(df -hkPBG / | tail -1 | awk '{print $2}')"

echo "Your disk size is now ${DSIZE}${UNIT}"
echo "And your / filesystem is ${FSSIZE}B"

sed -i "/\/tmp\/printsize/d" /root/.bash_profile

echo "The results of all commands are in /var/log/vm_resize.log"

rm $0

EOF
chmod +x /tmp/printsize
}

echo "This script will extend your disk partition and filesystem."
echo "This script will ONLY work with the Nagios XI provided OVA VM image"
echo "If you have modified your partitioning or your filesystem please don't execute this script"
echo "Your Nagios XI server will reboot with the extended filesystem"

while true; do
    read -p "Do you want to continue running this script? [y/n] " yn
    case $yn in
        [Yy]*  | "" ) 
			rm $0
			echo "User initiated VM disk resize" >> /var/log/vm_resize.log	
			extendfs
			printsize
			echo -e "d\n2\nn\np\n2\n\n+\nt\n2\n8e\nw" | fdisk /dev/sda &>> /var/log/vm_resize.log
			echo "/tmp/extendfs" >> /usr/local/run.sh
			shutdown -r now
			break;;
        [Nn]* ) 
			exit;;
        * ) echo "Please answer yes or no.";;
    esac
done



