#!/bin/bash 
# Info: Installation for Provisioning
# Author: JesusPerezLorenzo 
# Release: 1.0.2
# Date: 14-11-2023

set +o errexit
set +o pipefail

INSTALL_PATH=${1:-/usr/local} 
INSTALL_BIN_PATH=${2:-/usr/local/bin} 
INSTALL_RUN_MODE=${3:-mode-ui} 

PACK_SET_ENV_LIST="core/bin/provisioning"

[ -r "provisioning/resources/ascii.txt" ] && cat "provisioning/resources/ascii.txt"
[ ! -d "provisioning" ] && echo "provisioning path not found"  && exit 1
[[ "$INSTALL_PATH" != /* ]] && INSTALL_PATH=$(pwd)/$INSTALL_PATH
if [ -d "$INSTALL_PATH/provisioning" ] ;then
   echo "Remove previous installation ... "
   sudo rm -rf "$INSTALL_PATH/provisioning" 
fi
if [ -n "$1" ] ; then 
   for file in $PACK_SET_ENV_LIST
   do
      case "$(uname)" in 
         Darwin) sed "s,/usr/local/,$INSTALL_PATH/,g" <"provisioning/$file" > /tmp/provisioning.$$
                  mv /tmp/provisioning.$$  "provisioning/$file"
                  ;;
         Linux) sed -i'' "s,/usr/local/,$INSTALL_PATH/,g"  "provisioning/$file"
               ;;
      esac
   done
   chmod +x provisioning/core/bin/provisioning 
fi

[ ! -d "$INSTALL_PATH" ] && sudo mkdir -p "$INSTALL_PATH" 
sudo rm -f install-provisioning
[ -d "$INSTALL_PATH/provisioning" ] && sudo rm -r $INSTALL_PATH/provisioning 
sudo cp -r provisioning "$INSTALL_PATH" 
sudo rm -f "$INSTALL_BIN_PATH/provisioning"
sudo ln -s "$INSTALL_PATH"/provisioning/core/bin/provisioning $INSTALL_BIN_PATH

if sudo $INSTALL_PATH/provisioning/core/bin/install_nu.sh install no-ask $INSTALL_RUN_MODE $INSTALL_BIN_PATH ; then
   export PROVISIONING=${PROVISIONING:-$INSTALL_PATH/provisioning}
   if sudo $INSTALL_PATH/provisioning/core/bin/install_config.sh install ; then 
      #sudo "$INSTALL_PATH/bin/provisioning install 
      sudo $INSTALL_PATH/bin/provisioning setup versions
      sudo $INSTALL_PATH/bin/provisioning setup middleware
      sudo $INSTALL_PATH/bin/provisioning setup tools check all 
      sudo $INSTALL_PATH/bin/provisioning setup providers check all 
   else
      echo "EROOR: installation config in $INSTALL_PATH."
      exit 1
   fi
else 
      echo "EROOR: installation in $INSTALL_PATH."
      exit 1
fi
echo "
✅ Installation complete in $INSTALL_PATH.
Use command 'provisioning -h' for help 
Thanks for install PROVISIONING
"
