#!/bin/bash
# Info: Script to generate distribution pack forProvisioning
# Author: JesusPerezLorenzo 
# Release: 1.0.2
# Date: 14-11-2023

set +o errexit
set +o pipefail

set -o allexport
## shellcheck disable=SC1090
[ -n "$PROVISIONING_ENV" ] && [ -r "$PROVISIONING_ENV" ] && source "$PROVISIONING_ENV"
[ -r "../env-provisioning" ] && source ../env-provisioning
[ -r "env-provisioning" ] && source ./env-provisioning
#[ -r ".env" ] && source .env set
set +o allexport

export PROVISIONING=${PROVISIONING:-/usr/local/provisioning}

ORG=$(pwd) 
pwd=$(pwd)

if [[ "$pwd"  == *provisioning* ]] ; then 
	while [ "$(basename $pwd)" != "provisioning" ]  && [ "$pwd" != "/"  ]
	do  
   		cd .. &&  pwd=$(pwd) 
	done
else 
	cd $PROVISIONING
  pwd=$(pwd)
fi
[ "$(basename "$pwd")" != "provisioning" ]  && echo "provisioning  path not found in $(pwd)"  && exit 1 

PROD_NAME=provisioning
PROD_SOURCE=${PROD_SOURCE:-$PROVISIONING}

PROD_LIST_PATH="distro/pack_list"
PROD_INSTALLER="taskservs/provisioning/default/installer"
PROD_HOWTO_INSTALLER="distro/howto-install"

WK_PATH=/tmp/pack.$$
PACK_PATH=provisioning
PROD_PACK_PATH=${PROD_PACK_PATH:-/tmp} 
PACK_HOWTO_INSTALLER="howto-$PROD_NAME"

[ ! -d "$WK_PATH/$PACK_PATH" ] && mkdir -p "$WK_PATH/$PACK_PATH"

tar -cf "$WK_PATH/$PROD_NAME.tar" -T "$PROD_LIST_PATH"  &&
cp "$PROD_SOURCE/$PROD_INSTALLER"  "$WK_PATH/install-$PROD_NAME" &&
cp "$PROD_SOURCE/$PROD_HOWTO_INSTALLER.txt"  "$WK_PATH/$PACK_HOWTO_INSTALLER.txt" &&
cp "$PROD_SOURCE/$PROD_HOWTO_INSTALLER.md"  "$WK_PATH/$PACK_HOWTO_INSTALLER.md" &&
cd "$WK_PATH/$PACK_PATH" &&
tar xf "$WK_PATH/$PROD_NAME.tar" &&
rm "$WK_PATH/$PROD_NAME.tar" &&
cd $WK_PATH && 
tar czf "$PROD_PACK_PATH/${PROD_NAME}.tar.gz" $PROD_NAME && 
cd $(dirname "$WK_PATH") && 
rm -rf "$WK_PATH"

echo "$PROD_NAME pack available in $PROD_PACK_PATH/${PROD_NAME}.tar.gz"

cd "$ORG" || exit 1

rm -fr "$WK_PATH"
