#!/bin/bash
# Python build tool ( /opt/cppython )
# copyright (c) syslint technologies

RED='\033[01;31m'
GREEN='\033[01;32m'
RESET='\033[0m'

export who=`whoami`
if [[ $who != "root" ]];then
    echo "You are unprivileged user. Please contact your server administrator" 
    exit 0
fi

### Set the required python version

DEFAULT_PY_VERSION='3.8.5'

### Don't change the following

# Show the usage of this script
help_info (){
cat << _EOF
copyright (c) Syslint Technologies
The  Python Build Tool ( /opt/cppython )

usage : /usr/local/cpanel/scripts/buildpython.sh [ options ]

   options:    

        --help          = To show this help
        --install       = Install the default python version
        --install version-number  = Install your custom python version. Python 3 is mandatory  
        --modinstall    =>  Install required python modules
_EOF
}


# To build custom python from source

build_python () {
_version=$1
_SOURCE="https://www.python.org/ftp/python/$_version/Python-$_version.tgz"
_BUILDPATH="/opt/cppython"
_SOURCEDIR="/usr/local/src/Python-$_version"
#yum install readline-devel bzip2-devel xz-devel sqlite-devel tkinter libffi-devel -y
cd /usr/local/src/
echo "Building Pyton : $1"
echo "Downloading from : $_SOURCE"
wget -c $_SOURCE
rm -rf Python-$_version
tar -xvzf Python-$_version.tgz
cd Python-$_version/
rm -rf $_BUILDPATH
echo "/opt/cppython/lib" > /etc/ld.so.conf.d/cppython.conf
cd $_SOURCEDIR/
pwd
# Building and installingPyhton
./configure  --prefix=/opt/cppython --enable-shared 
make -j`nproc`
make install
ldconfig
# upgrading pip3 from python repo
/opt/cppython/bin/pip3 install --upgrade pip
echo "Installing Python modules"
/opt/cppython/bin/pip3 install wheel
/opt/cppython/bin/pip3 install paramiko mysqlclient==2.0.1  pexpect ftputil pysftp boto3 Mako PyYAML
/opt/cppython/bin/pip3 list
cd /usr/local/src
rm -rf Python-$_version
echo "Python installation completed on $_BUILDPATH with the version $_version"
exit 0
}

mod_install () {
    echo "Installing python modules"
    /opt/cppython/bin/pip3 install --upgrade pip
    /opt/cppython/bin/pip3 install --upgrade wheel
    /opt/cppython/bin/pip3 install --upgrade paramiko mysqlclient==2.0.1  pexpect ftputil pysftp boto3 Mako PyYAML
    /opt/cppython/bin/pip3 list
}
verre='^[0-9]\.([0-9]|[0-9]{2})\.([0-9]|[0-9]{2})$'

if [ "$1" == "" ];then
    help_info
elif [ "$1" == "--help" ];then
    help_info
elif [ "$1" == "--install" ];then
    if [ "$2" == "" ];then
        _BUILD_VER=$DEFAULT_PY_VERSION
         build_python $_BUILD_VER
    elif ! [[ $2 =~ $verre ]];then
        echo "Invalid python version"
        exit 0
    else
         _BUILD_VER=$2
         build_python $_BUILD_VER
    fi
elif [ "$1" == "--modinstall" ];then
    mod_install
else
    help_info
fi

