#!/bin/bash

# Check if envsubst is installed and install it if necessary
if ! command -v envsubst &>/dev/null; then
  echo "envsubst not found, installing gettext package"

  if command -v apk &>/dev/null; then
    # Alpine
    apk add --no-cache gettext
  elif command -v apt-get &>/dev/null; then
    # Debian-based distributions
    apt-get update && apt-get install -y gettext
  elif command -v yum &>/dev/null; then
    # RHEL-based distributions
    yum install -y gettext
  else
    echo "Unsupported Linux distribution. Please install gettext manually."
    exit 1
  fi
fi

export DEPLOYS=$(helm ls --all-namespaces | grep $RELEASE_NAME | wc -l)

echo "---------------------------------------------------------------------------------------------"
echo "Existing deployments found: $DEPLOYS"
echo "---------------------------------------------------------------------------------------------"


# Replace name of application in Chart Templates
sed -i "s/APP_NAME/${APPLICATION_NAME}/g" ../${CHART_DIR}/Chart.yaml
sed -i "s/APP_NAME/${APPLICATION_NAME}/g" ../${CHART_DIR}/stacks/${STACK}/values.yaml

# Replace variables from CICD env variables in that files
envsubst < ../${CHART_DIR}/stacks/${STACK}/values.yaml > ../${CHART_DIR}/stacks/${STACK}/values_tmp.yaml
cp ../${CHART_DIR}/stacks/${STACK}/values_tmp.yaml ../${CHART_DIR}/stacks/${STACK}/values.yaml

# Image Tag fix
if [ -z "${TAG:-}" ]; then
    TAG=$1
else
    TAG=$(echo ${TAG} | sed 's/\//-/g;s/_/-/g')
fi

if [ -n "${SET_IMAGE:-}" ]; then
    echo -e "\n - Custom image defined in gitlab-ci.yml"
    echo "${SET_IMAGE}"
    IMAGE_NAME=$(echo "${SET_IMAGE}" | awk -F: '{print $1}')
    TAG=$(echo "${SET_IMAGE}" | awk -F: '{print $2}')
fi

echo -e "\n---------------------------------------------------------------------------------------------\n"
echo -e "\n IMAGE TO DEPLOY: ${IMAGE_NAME}:${TAG}"
echo -e "\n---------------------------------------------------------------------------------------------\n"

helm dependency update ../${CHART_DIR}

function install_chart {
    local cmd="helm install ${RELEASE_NAME} --namespace ${NAMESPACE} --set image.repository=${IMAGE_NAME} --set image.tag=${TAG} --set Namespace=${NAMESPACE} ../${CHART_DIR} --wait --values=../${CHART_DIR}/stacks/${STACK}/values.yaml $1"
    echo "Executing command: ${cmd}"
    eval "${cmd}"
}

function upgrade_chart {
    local cmd="helm upgrade ${RELEASE_NAME} --namespace ${NAMESPACE} --set image.repository=${IMAGE_NAME} --set image.tag=${TAG} --set Namespace=${NAMESPACE} ../${CHART_DIR} --wait --values=../${CHART_DIR}/stacks/${STACK}/values.yaml $1"
    echo "Executing command: ${cmd}"
    eval "${cmd}"
}

if [ ${DEPLOYS} -eq 0 ]; then
    echo "---------------------------------------------------------------------------------------------"
    echo "Proceeding with the installation of $RELEASE_NAME"
    echo "---------------------------------------------------------------------------------------------"
    if [ "${DEBUG}" = "true" ]; then
        install_chart "--debug"
    else
        install_chart
    fi
else
    echo "---------------------------------------------------------------------------------------------"
    echo "Upgrading existing deployment of $RELEASE_NAME"
    echo "---------------------------------------------------------------------------------------------"
    if [ "${FORCE_DEPLOY}" = "true" ]; then
        if [ "${DEBUG}" = "true" ]; then
            upgrade_chart "--force --debug"
        else
            upgrade_chart "--force"
        fi
    else
        if [ "${DEBUG}" = "true" ]; then
            upgrade_chart "--debug"
        else
            upgrade_chart
        fi
    fi
fi

# SENT NOTIFICATION
# Get the exit status of the last command
EXIT_STATUS=$?

# Function to send notification to slack
send_notification() {
    local STATUS=$1
    local MESSAGE=$2

    echo -e "${MESSAGE}"
    scripts/notify-slack-deploy.sh ${STATUS}
}

echo -e "\n---------------------------------------------------------------------------------------------"
# Check if the exit status is not 0 (indicating an error)
if [ $EXIT_STATUS -ne 0 ]; then
    # Rollback the release to the previous version
    echo -e "\n - Rolling back application"
    helm rollback --namespace ${NAMESPACE} ${RELEASE_NAME} 0
    ROLLBACK_STATUS=$?

    # Check if the rollback was successful
    if [ $ROLLBACK_STATUS -ne 0 ]; then
        send_notification ${ROLLBACK_STATUS} "\n - Rollback failed. Please check the application status and consider rolling back manually."
    else
        send_notification ${EXIT_STATUS} "\n - Rollback successful. Application has been rolled back to the previous version."
    fi
else
    # Send a notification about the deployment status
    send_notification ${EXIT_STATUS} "\n - Deployed Successfully. Sending Notification to slack..."
fi


echo -e "\n  - Insert status of deploy in ElasticSearch..."
scripts/notifications/notify_deploy_elastic.sh ${EXIT_STATUS}

exit $EXIT_STATUS
