#!/bin/bash
# Info: Script to instal Provisioning from repo 
# Author: JesusPerezLorenzo  
# Release: 1.0.2
# Date: 11-11-2023

set +o errexit
set +o pipefail

# Root path 

# clone CORE

# Install tasks

# Install providers 

# Install klouds model 

# Install ENV and cnpro command 

export PROVISIONING=${PROVISIONING:-$HOME/provisioning}
export PROVIISONING_KLOUDS=${PROVIISONING_KLOUDS:-$HOME/kloud}
export RUN_PATH=${RUN_PATH:-$PROVISIONING/providers}

USAGE="provisioning provider upcloud | aws | local  -k cloud-path  file-settings.yaml  provider-options "

[ "$1" == "-x" ] && set -x && debug=-x && shift

[ "$1"  == "-h"  ] && echo "$USAGE" && exit 

[ "$1"  == "-p"  ] && PROVIDER="$2" && shift 2

if [ -n "$1" ] && [ -z "$PROVIDER" ] ; then 
   if [ -d "$RUN_PATH/$1" ] &&  [ -r "$RUN_PATH/$1/on_${1}_server" ] ; then 
      PROVIDER=$1
      shift
   fi
fi
if [ -z "$PROVIDER" ] ; then 
   base_path=$(basename "$(pwd)")
   [ -d "$RUN_PATH/$base_path" ] &&  [ -r "$RUN_PATH/$base_path/on_${base_path}_server" ] && PROVIDER=$base_path
fi

[ -z "$PROVIDER" ] && PROVIDER=$1 && shift

if [ "$1"  == "-k"  ] ; then 
   if [ -d "$PROVIISONING_KLOUDS/$2" ] ; then
      PROVIISONING_KLOUDS="$PROVIISONING_KLOUDS/$2"  
   else
      [ -d "$2" ] && PROVIISONING_KLOUDS="$2"  
   fi
   shift 2
fi

[ ! -d "$RUN_PATH/$PROVIDER" ] && echo "Provider $PROVIDER not found in $RUN_PATH"  && exit 1	
RUN_PATH="$RUN_PATH/$PROVIDER" 
   
[ ! -r "$RUN_PATH/on_${PROVIDER}_server"  ] && echo "Provider server on_${PROVIDER}_server not found in $RUN_PATH"  && exit 1 

## Path for cloud local tasks definition could not exist if all tasks are using library install mode from 'lib-tasks'
#export RUN_TASKS_PATH="tasks"
# Defaul user for tasks operations via SSH it depends on OS Distribution installer 
#export SSH_USER=${SSH_USER:-admin}

if [ -d "$PROVIISONING_KLOUDS/$PROVIDER" ] ; then 
   cd "$PROVIISONING_KLOUDS/$PROVIDER" || exit 1
else
  cd "$PROVIISONING_KLOUDS" || exit 1
fi

$RUN_PATH/on_${PROVIDER}_server $debug "$@"
