#!/bin/bash
# Info: Script to run provisioning (Provisioning) from a webhook call 
# Author: JesusPerezLorenzo 
# Release: 1.0.2
# Date: 19-11-2023
#
USAGE="on_webhook_provisioning env-fils"

[ "$1" == "-h"  ] && echo "$USAGE" && exit
[ "$1" == "-i" ] || [ "$2"  == "-i" ] && echo "$(basename "$0") $(grep "^# Info:" "$0" | sed "s/# Info: //g") " && exit
[ "$1" == "-v" ] || [ "$2"  == "-v" ] && grep "^# Release:" "$0" | sed "s/# Release: //g" && exit

set -x

set +o errexit
set +o pipefail

ROOT_PATH=$(dirname "$0") 

[ -z "$1" ] && echo "No env path found to load settings" && exit 1

.  "$1" 
[ -r "$HOME/env-provisioning" ]  && .  "$HOME/env-provisioning" 


PROVISIONING_CMD=$(type -P provisioning) 

[ -z  "$PROVISIONING_CMD" ] && echo "provisioning command not found" && exit 1 

PROVIISONING_KLOUD=${PROVIISONING_KLOUD:-$HOME/kloud}

ORG=$(pwd)

[ -z "$REPO_SSH_URL" ] && echo "No REPO_SSH_URL found" && exit 1
[ -z "$REPO_FULLNAME" ] && echo "No REPO_FULLNAME found" && exit 1

REPO_DIR=$(dirname "$REPO_FULLNAME")
REPO_NAME=$(basename "$REPO_FULLNAME")
[ -z "$REPO_DIR" ] && [ -z "$REPO_NAME "]  && echo "Error REPO_FULLNAME"  && exit 1

[ ! -d "$PROVIISONING_KLOUD/$REPO_DIRNAME" ] && mkdir -p "$PROVIISONING_KLOUD/$REPO_DIRNAME" 

cd  "$PROVIISONING_KLOUD/$REPO_DIRNAME" 

if [ ! -d "$REPO_NAME" ] ; then
	if ! git clone --recurse-submodules "$REPO_SSH_URL" ; then 
	  echo "Error clone $REPO_SSH_URL"
	  exit 1
	fi
	cd "$REPO_NAME"
else
	cd "$REPO_NAME"
	git pull 2>/dev/null
fi

[ -z "$RUN_COMMIT_MSG" ] && exit 0 

[ -r "./env-provisioning" ] && . "./env-provisioning"

WK_LOG_RUN=/tmp/on_provisioning_log.$$
WK_ERR_RUN=/tmp/on_provisioning_err.$$

# Check if AI webhook processing is enabled and message should be processed by AI
if [ -n "$WEBHOOK_AI_ENABLED" ] && [ "$WEBHOOK_AI_ENABLED" = "true" ] && [ -n "$WEBHOOK_MESSAGE" ]; then
    # Process webhook message with AI first
    AI_RESULT=$(nu -c "
        use core/nulib/lib_provisioning/webhook/ai_webhook.nu test_webhook
        test_webhook '$WEBHOOK_MESSAGE' --platform '${WEBHOOK_PLATFORM:-generic}' --user '${WEBHOOK_USER:-webhook}' --channel '${WEBHOOK_CHANNEL:-webhook}'
    " 2>/dev/null)
    
    if [ $? -eq 0 ]; then
        echo "AI processed webhook message: $WEBHOOK_MESSAGE" >> "$WK_LOG_RUN"
        echo "AI result: $AI_RESULT" >> "$WK_LOG_RUN"
    fi
fi

$PROVISIONING_CMD $RUN_COMMIT_MSG >"$WK_LOG_RUN" 2>"$WK_ERR_RUN"

mv "$WK_LOG_RUN" run.log 
mv "$WK_ERR_RUN" error.log 

git add *
git commit -m "chore: running form on_webhook_provisioning: \"$RUN_COMMIT_MSG\""

if ! git push ; then 
	echo "Error push  $REPO_SSH_URL"
	exit 1
fi
