# !!! BE CAUTIOUS WITH UNCOMMITED CHANGES BEFORE RUNNING THIS SCRIPT AS IT WILL SWITCH BRANCHES !!!

#ONLY ADMINISTRATORS OF THE REPOSITORY CAN RUN THIS SCRIPT
#OTHERWISE YOU WON'T BE ABLE TO PUSH CHANGES TO GH-PAGES

# THE SCRIPT NEEDS TO BE RUN WITH A PYTHON VENV ACTIVATED REQUIREMENTS FROM INFAMOUS-DOCS-CEA INSTALLED

#!/bin/bash

# Change the current directory to the script directory
BASEDIR=$(dirname "$0")
cd $BASEDIR
# Look for the .env file
while [[ "$PWD" != "$HOME" && ! -e .env ]]; do cd ..; done
if [[ -e .env ]]; then
  ENVFILEDIR=$PWD
  set -a; source .env; set +a
  echo "Using .env file found in $PWD"
else
  echo "CANCELED"
  echo "  No .env file found in the directory tree."
  echo "  Please setup the .env file and retry"
fi

# Check if the number of arguments is correct
if (($# != 1))
then
    echo " "
    echo "CANCELED"
    echo "  Wrong number of arguments : $# were provided but 1 is expected (commit_message)"
    echo "  Syntax : ./tools/admin/publish_documentation.sh commit_message"
    echo "  Example:"
    echo "      To publish the site following an update in the tools section:"
    echo "      ./tools/admin/publish_documentation.sh "updated the tools section""
    exit
fi

# Change the current directory to the home directory
cd $INFAMOUSDIR
echo "EXECUTED FROM $PWD"

#get current branch
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)

# Switch to gh-pages branch and pull
git fetch origin
if git show-ref --verify --quiet refs/heads/gh-pages; then
  git checkout gh-pages
  git pull origin gh-pages
else
  git checkout -b gh-pages origin/gh-pages
fi

# Remove old docs
rm -r ./docs

# Add and commit changes
git add ./docs
git commit -m "reset site"  

# Switch back to main branch
git checkout $CURRENT_BRANCH

# Navigate to project directory
cd projects-cea/infamous-docs-cea
#generate the sql page
python ./src/sqlsnipit.py || exit 1
#build the docs
mkdocs build || exit 1
git checkout -- ./content/sql.md


# Switch back to gh-pages branch
git checkout gh-pages

# Navigate back to root directory
cd ../..

# Add new docs and commit changes
git add ./docs/*
git commit -m "update site: $1"

# Push changes to gh-pages branch
git push origin gh-pages

# Switch back to main branch
git checkout $CURRENT_BRANCH
