#!/bin/bash
# Author:  EinicYeo <einicyeo AT gmail.com>
# BLOG:  https://www.infvie.com
#
# Notes: EnvoyinStack for CentOS/RedHat 6+

Install_Python() {
  if [ -e "${python_install_dir}/bin/python" ]; then
    echo "${CWARNING}Python already installed! ${CEND}"
  else
    pushd ${envoyinstack_dir}/src > /dev/null

    if [ "${PM}" == 'yum' ]; then
      [ -z "`grep -w epel /etc/yum.repos.d/*.repo`" ] && yum -y install epel-release
      pkgList="gcc dialog augeas-libs openssl openssl-devel libffi-devel redhat-rpm-config ca-certificates"
      for Package in ${pkgList}; do
        yum -y install ${Package}
      done
    fi

    # Install Python3
    if [ ! -e "${python_install_dir}/bin/python" -a ! -e "${python_install_dir}/bin/python3" ] ;then
      tar xzf Python-${python_ver}.tgz
      pushd Python-${python_ver} > /dev/null
      ./configure --prefix=${python_install_dir}
      make && make install
      [ ! -e "${python_install_dir}/bin/python" -a -e "${python_install_dir}/bin/python3" ] && ln -s ${python_install_dir}/bin/python{3,} 
      [ ! -e "${python_install_dir}/bin/pip" -a -e "${python_install_dir}/bin/pip3" ] && ln -s ${python_install_dir}/bin/pip{3,} 
      [ -z "`grep ^'export PATH=' /etc/profile`" ] && echo "export PATH=${python_install_dir}/bin:\$PATH" >> /etc/profile
      [ -n "`grep ^'export PATH=' /etc/profile`" -a -z "`grep ${python_install_dir} /etc/profile`" ] && sed -i "s@^export PATH=\(.*\)@export PATH=${python_install_dir}/bin:\1@" /etc/profile
      . /etc/profile
      popd > /dev/null
    fi

    if [ ! -e "${python_install_dir}/bin/pip" ]; then
      unzip -q setuptools-${setuptools_ver}.zip
      tar xzf pip-${pip_ver}.tar.gz
      pushd setuptools-${setuptools_ver} > /dev/null
      ${python_install_dir}/bin/python setup.py install
      popd > /dev/null
      pushd pip-${pip_ver} > /dev/null
      ${python_install_dir}/bin/python setup.py install
      popd > /dev/null
    fi

    if [ ! -e "/root/.pip/pip.conf" ] ;then
      # get the IP information
      PUBLIC_IPADDR=$(../include/get_public_ipaddr.py)
      IPADDR_COUNTRY=$(../include/get_ipaddr_state.py ${PUBLIC_IPADDR})
      if [ "${IPADDR_COUNTRY}"x == "CN"x ]; then
        [ ! -d "/root/.pip" ] && mkdir /root/.pip
        echo -e "[global]\nindex-url = https://mirrors.aliyun.com/pypi/simple/" > /root/.pip/pip.conf
      fi
    fi

    if [ -e "${python_install_dir}/bin/python3" ]; then
      echo "${CSUCCESS}Python ${python_ver} installed successfully! ${CEND}"
      rm -rf Python-${python_ver}
    fi
    popd > /dev/null
  fi
}

Uninstall_Python() {
  if [ -e "${python_install_dir}/bin/python" ]; then
    echo "${CMSG}Python uninstall completed${CEND}"
    rm -rf ${python_install_dir}
  fi
}
