#!/bin/bash

ACSIA_PREPARE_ENVIRONMENT="acsia_prepare_environment"
ACSIA_HOME="/home/acsia"
SUPPORTED_DISTRO=("Ubuntu 20.04+" "CentOS 7")
DISTRO_FOUND="NONE"
VERSION=0
CRED_FILE="credentials.txt"
CURR_DIR=$(pwd)
ACSIA_DOWNLOAD_URL="https://nexus.acsia.io/repository/v6-releases/scripts/acsia_download"
ACSIA_DOWNLOAD_FILE="acsia_download"
ACSIA_USER="acsia"

set -e
usage() {
    echo "The $ACSIA_PREPARE_ENVIRONMENT must be executed with root privileges"
    echo "Usage: $ACSIA_PREPARE_ENVIRONMENT"
    echo "no parameters are accepted"
}


download_error() {
    echo "Error while downloading $ACSIA_DOWNLOAD_FILE from $ACSIA_DOWNLOAD_URL."
    echo "Try to execute manually 'curl -u YOUR_USERNAME:YOUR_PASSWORD -v --fail $ACSIA_DOWNLOAD_URL -o $ACSIA_DOWNLOAD_FILE' to understand the reason."
}


distro_unsupported() {

    if [[ "${DISTRO_FOUND}" == "NONE" ]]; then
       echo "Unable to find your Linux distribution. Exiting"
    else
        echo "Your Linux $DISTRO_FOUND $VERSION is not supported. Supported distros are: ${SUPPORTED_DISTRO[@]}"
    fi
    exit 1
}

check_linux_version() {

    if [ -f /etc/debian_version ]; then
        if [ -f /etc/lsb-release ]; then
            . /etc/lsb-release
            DISTRO=$DISTRIB_ID
            VERSION=${DISTRIB_RELEASE%%.*}
        else
            DISTRO="Debian"
            VERSION=$(cat /etc/debian_version | cut -d'.' -f1)
        fi

        case "$DISTRO" in
            "Ubuntu")
                DISTRO_FOUND="$DISTRO"
                SUDOERS_GROUP="sudo"
                if [ "$VERSION" -ge 20 ]; then
                    prepare_environment
                else
                    distro_unsupported
                fi
                ;;


            "Debian")
                 DISTRO_FOUND="$DISTRO"
                 SUDOERS_GROUP="sudo"
                 distro_unsupported
                ;;


            *)
                distro_unsupported
                ;;

        esac

    elif [ -f /etc/system-release-cpe ]; then
        DISTRO=$(cat /etc/system-release-cpe | cut -d':' -f3)
        VERSION=$(cat /etc/system-release-cpe | cut -d':' -f5 | cut -d'.' -f1 | sed 's/[^0-9]*//g')

        case "$DISTRO" in

            "centos")
                DISTRO_FOUND="$DISTRO"
                SUDOERS_GROUP="wheel"
                if [ "$VERSION" -eq 7 ]; then
                    prepare_environment
                else
                    distro_unsupported
                fi
                ;;

            *)
                distro_unsupported
                ;;

        esac
    else
        distro_unsupported
    fi

}


print_linux_version() {
    echo "Found $DISTRO_FOUND $VERSION"
}

prepare_environment() {

  print_linux_version
  read_credentials_file

 if ! download_acsia_download; then
      download_error
      exit 1
 else
     echo "The acsia_download script has been downloaded."
 fi

 if ! install_dependencies; then
	echo "An error occurred while installing os dependencies. Please verify that your package manager is working good"
        exit 1
 fi

 if ! create_acsia_user; then
        echo "An error occurred creating acsia user."
        exit 1
 fi

 if ! acsia_user_passwordless; then
        echo "An error occurred while configuring acsia as a passwordless sudoer."
        exit 1
 fi

 if ! download_acsia_package; then
        echo "An error occurred while downloading the acsia package."
        exit 1
 fi

  exit 0
}

create_acsia_user() {

 if id -u "$ACSIA_USER" >/dev/null 2>&1; then
   #Check if the acsia user is member of the sudoers group
   if ! id -nG "$ACSIA_USER" | grep -i "$SUDOERS_GROUP"; then
     usermod -a -G "$SUDOERS_GROUP" "$ACSIA_USER"
   fi
 else
   useradd -m -d "$ACSIA_HOME" -c "ACSIA Service User" -G "$SUDOERS_GROUP" "$ACSIA_USER" -s /bin/bash

 fi


}

acsia_user_passwordless() {

 if ! grep "$ACSIA_USER ALL=(ALL)       NOPASSWD: ALL" /etc/sudoers; then
     echo "$ACSIA_USER ALL=(ALL)       NOPASSWD: ALL" >> /etc/sudoers
 fi

}


download_acsia_package() {

  cp "$ACSIA_DOWNLOAD_FILE" "$ACSIA_HOME/"
  touch "$ACSIA_HOME/.sudo_as_admin_successful"
  chown -R "$ACSIA_USER"."$ACSIA_USER" "$ACSIA_HOME/"
  chmod +x  "$ACSIA_HOME/$ACSIA_DOWNLOAD_FILE"
  cd "$ACSIA_HOME"
  su -c "/usr/bin/python3 $ACSIA_HOME/acsia_download --user \"$NEXUS_USERNAME\" --password \"$NEXUS_PASSWORD\"" -m "$ACSIA_USER"
  su - "$ACSIA_USER"

}

download_acsia_download() {
   echo "Downloading the acsia_download script"
   curl -u "$NEXUS_USERNAME:$NEXUS_PASSWORD" --fail "$ACSIA_DOWNLOAD_URL" -o "$ACSIA_DOWNLOAD_FILE"

}

install_dependencies(){

   if [ -z "$DISTRO" ];then
        echo "Your linux distribution is unknown. Cannot install dependencies"
        exit 1
  fi

   case "$DISTRO" in
            "Ubuntu")

                if ! install_ubuntu_dependencies; then
      		      exit 1
 		fi
               ;;

            "centos")

                if ! install_centos_dependencies; then
                      exit 1
                fi
               ;;



            *)
                distro_unsupported
                ;;

        esac



}

install_centos_dependencies(){

  echo "Installing preliminary os dependencies."
  yum install -y python3 python3-pip python3-devel
  pip3 install --upgrade pip
  pip3 install requests

}

install_ubuntu_dependencies(){

  echo "Installing preliminary os dependencies."
  apt update
  apt install -y python3 python3-pip

}

read_credentials_file() {

  if [ -f $CRED_FILE ]; then
    NEXUS_USERNAME=$(grep Username $CRED_FILE | cut -d ' ' -f2 | tr -d '\r' | tr -d '\n')
    NEXUS_PASSWORD=$(grep Password $CRED_FILE | cut -d ' ' -f2 | tr -d '\r' | tr -d '\n')
  else
    echo "Please upload the $CRED_FILE in the $CURR_DIR directory."
  fi

  if [ -z "$NEXUS_USERNAME" ]  || [ -z "$NEXUS_PASSWORD" ];then
	echo "The $CRED_FILE is not in the right format please be sure it contains Username and Password in different rows."
	exit 1
  fi

}


if [ $# -ne 0 ]; then
   usage
   exit 1
fi


if [ "$EUID" -ne 0 ]
  then echo "$ACSIA_PREPARE_ENVIRONMENT must be run as root (or with sudo)."
  exit
fi

check_linux_version
