#!/bin/bash

    << CHANGELOG
    2021-03-09: Initial Creation & Add to GIT
CHANGELOG


if [[ "$EUID" -ne 0 ]]; then
	echo "This installer needs to be run with superuser privileges."
	exit
fi




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Python-01] - Apt upate
$(tput sgr 0)
"

apt -qq update




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Python-02] - Install Dependency Packages
$(tput sgr 0)
"

apt -qq install -y make build-essential libssl-dev zlib1g-dev && \
apt -qq install -y libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm && \
apt -qq install -y libncurses5-dev  libncursesw5-dev xz-utils tk-dev




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Python-03] - Download Latest source file to home directory
$(tput sgr 0)
"

wget https://www.python.org/ftp/python/3.9.2/Python-3.9.2.tgz




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Python-04] - Extract & enter directory
$(tput sgr 0)
"

tar xvf Python-3*.tgz && pushd "$(find . -type d -name "Python-3*" -print -quit)"




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Python-05] - Run configure to prepare the build
$(tput sgr 0)
"

./configure --enable-optimizations




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Python-05] - Compile it. 
       ** Note: Using altinstall prevents replacing the default python binary at /usr/bin/python
$(tput sgr 0)
"

sudo make altinstall




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-06] - Verify python version. ** MUST use the build number as part of the command
$(tput sgr 0)
"

    : ' (Alternate Method)
popd > /dev/null && \
pushd /usr/bin/ > /dev/null && \
App=`basename "$(find . -name "python*" -print -quit)"` && \
echo -e "$(tput setaf 7; tput setab 0)" && \
${App} --version && \
echo -e "$(tput sgr 0)"
    '

Version=`cat Makefile | grep "^VERSION=" | awk -F " " '{ print $NF }'` && \
echo -e "$(tput setaf 7; tput setab 0)" && \
python${Version} --version && \
echo -e "$(tput sgr 0)" && \
popd > /dev/null




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-07] - Upgrade pip module
$(tput sgr 0)
"

python${Version} -m pip install --upgrade pip




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-08] - Add pip to PATH variable
$(tput sgr 0)
"

    # TODO
    : '
    WARNING: The scripts pip, pip3 and pip3.9 are installed in '/home/www-svc/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

    '


echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-09] - Deployment Script Cleanup
$(tput sgr 0)
"

if ! command -v realpath &> /dev/null
then
    echo -e "COMMAND 'realpath' could not be found. $(tput setaf 3; tput setab 0)Please move script manually.$(tput sgr 0)"
else
    SCRIPT=`realpath -s $0` && \
    DESTINATION=~/Deploy && \
    mkdir -p ${DESTINATION} && \
    mv ${SCRIPT} ${DESTINATION} && \
    ls -laR ${DESTINATION}
fi
