#!/bin/sh

# OnApp	Control Panel installation script
# Paul Morris (paul@onapp.com) 

UPDATE=`which yum`
CDNURL="cdn.rpm.repo.onapp.com/repo/centos/5"
INSDIR="onapp_`date +%d%m%y%H%M`"
LOG="onapp_`date +%d%m%y%H%M`.log"

function f_progress {
    COUNT=${1}
    while [ ${COUNT} -gt 0 ]; do
        echo -n "##"
        sleep 1
        COUNT=`/usr/bin/expr ${COUNT} - 1`
    done
    echo -e "\n"
}

echo -e "Staring OnApp Cloud Controller Installation\n\
- All output will be stored on ~/${INSDIR}/${LOG}"

if [ ! -e "~/${INSDIR}" ]; then
    mkdir ~/${INSDIR}
    touch ~/${INSDIR}/${LOG}
else
    touch ~/${INSDIR}/${LOG}
fi

if [ `whoami` != "root" ]; then
    echo "Error: You must be root ro run this script"
    exit 1;
fi

if ! uname -a | grep -w x86_64 &>/dev/null; then
    echo "Error: CentOS installation must be 64bit"
    exit 1
fi

if ! grep "CentOS release 5" /etc/redhat-release &>/dev/null; then
    echo "Error: CentOS installation must be CentOS 5.x"
    exit 1
fi

# Update CentOS
echo "- Running full system update using yum"
f_progress "5"
${UPDATE} -y update
f_progress "5"
if [ $? -eq 1 ]; then
    echo "Error: Failed to update OS installation"
    exit 1;
else
    echo "- Cleaining up after install"
    ${UPDATE} clean all &> ~/${INSDIR}/${LOG}
fi

## Install OnApp Controller

# Check selinux config
echo " - Cheking selinux config"
if [ -e "/etc/selinux/config" ]; then
    if [ `selinuxenabled ;echo $?` -eq 0 ]; then
        echo " -- Your CentOS installation has selinux enabled, trying to disable it..."
        echo -ne "SELINUX=disabled\nSELINUXTYPE=targeted\n" > /etc/selinux/config
        setenforce 0 &>/dev/null
        echo " --- You MUST reboot now to fully disable selinux, once rebooted you can run this script again"
        exit 0;
    else
        echo " -- selinux is already disabled"
    fi
else
    echo "Error: selinux config file is missing"
    exit 1;
fi

echo "- Downloading OnApp repository data"
wget http://${CDNURL}/onapp-repo.noarch.rpm -O ~/onapp-repo.noarch.rpm &> ~/${INSDIR}/${LOG}
if [ ! -e "/root/onapp-repo.noarch.rpm" ]; then
    echo "Error: Failed to download installation package"
    exit 1;
else  
    echo "- Installing OnApp repository data"
    rpm -ivh --replacepkgs ~/onapp-repo.noarch.rpm &> ~/${INSDIR}/${LOG}
    if [ $? -eq 1 ]; then
        echo "Error: Failed to install OnApp package"
        exit 1;
    else
	${UPDATE} clean all &> ~/${INSDIR}/${LOG}
	echo "- Installing OnApp controller"
	f_progress "5"
	${UPDATE} -y install onapp-cp-install 
	f_progress "5"
	if [ $? -eq 1 ]; then
            echo "Error: Failed to install OnApp controller"
            exit 1;
        else
	    echo "- Starting the OnApp controller installation in 5 seconds..."
	    while [ ${COUNT} -gt 0 ]; do
	        echo -n "${COUNT} "
	        sleep 1
	        COUNT=`/usr/bin/expr ${COUNT} - 1`
	    done
	    f_progress "5"
	    /onapp/onapp-cp-install/onapp-cp-install.sh
   	    f_progress "5"
	fi
    fi
fi
