#!/bin/bash
echo $1
port="38088"
pypihost="mirrors.myhuaweicloud.com"
bucket="mrs-samples-bootstrap-ap-southeast-2"
obshost="obs.ap-southeast-2.myhwclouds.com"

function downloadInitFiles()  
{
    yum -y install wget
    echo "******************downloading init files*****************"
    SOFTWARE_HOME='/home/software/superset'
    rm -fr $SOFTWARE_HOME
    mkdir -p $SOFTWARE_HOME
    cd $SOFTWARE_HOME
   wget http://${pypihost}/repo/pip.tar.gz
   wget --no-check-certificate https://${bucket}.${obshost}/superset/create_admin.exp
   wget --no-check-certificate https://${bucket}.${obshost}/superset/pip_hec.conf
}


function installPip()
{
    echo "******************install pip*****************"
    ##### install pip
    tar -zxf pip.tar.gz
    cd pip-* 
    python setup.py install
    cd ..
	mkdir ~/.pip
	cp pip_hec.conf ~/.pip/pip.conf
}

function pipInstall()
{
   yes | pip install  $*
}

function installOSLib()
{
    ###### install  
    echo "******************begin to install OS libary*****************"
    yum -y install gcc gcc-c++ libffi-devel python-devel-2.7.5-58.h6 python-pip python-wheel openssl-devel libsasl2-devel openldap-devel libsasl2-modules-gssapi-mit sasl2-bin
}


function useVirtualEnv()
{
    pipInstall virtualenv
    virtualenv venv
    . ./venv/bin/activate	
}

function installPipLib()
{
    echo "******************begin to install python libary*****************"
    ###
    yum -y install python-setuptools

    pipInstall --upgrade setuptools pip    
    pipInstall six  
    pipInstall bit_array  
    pipInstall thrift  
    pipInstall thrift_sasl==0.2.1  
    pipInstall sasl  
    pipInstall sqlalchemy  
    pipInstall impyla
    pipInstall flask-appbuilder
    pipInstall gssapi  
}

function installSuperset()
{
    echo "******************begin to install superset*****************"
    pipInstall superset==0.22.1
    #####
	chmod +x ${SOFTWARE_HOME}/create_admin.exp
    ${SOFTWARE_HOME}/create_admin.exp   
    superset db upgrade
    superset load_examples
    superset init
    ##start superset as daemon
    nohup superset runserver -d -a 0.0.0.0 -p ${port} 2>&1 -w 2 > superset.log &
    if [ $? -ne 0 ]; then
    	echo "======ERROR! install failed ."   | tee -a ${SOFTWARE_HOME}/install.log
    	exit 1 
    fi 
    
    echo "install software success"
}

function main()
{
    downloadInitFiles
    installPip
    installOSLib
    useVirtualEnv
    installPipLib
    installSuperset
}

main

