#!/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

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

# if a specific test is provided, use it
if [ -n "$1" ]; then
    specific_test="test_$1.py"
fi

# run the tests
pytest test/$specific_test

# check if the tests passed (return code 0)
if [ $? -eq 0 ]; then
    echo " "
    echo "Building distribution file for djagitit"
    # Get the version number from the setup.py file
    line=$(grep -m 1 'version' djagitit/setup.py)
    version=$(echo $line | cut -d"'" -f 2)
    # Check if the dist with the same version already exists
    if [ -f "./dist/djagitit-$version-py3-none-any.whl" ]; then
        echo "Dist with the same version already exists : version $version"
        # if the dist already exists, ask the user if they want to rebuild it
        read -p "Do you want to proceed anyway? (Y/n)" answer
        # if the answer is yes, rebuild the dist
        if [ "$answer" = "Y" ]; then
            echo "Rebuild distribution for version $version"
            python ./djagitit/setup.py bdist_wheel
        fi
    else
        # if the dist doesn't exist, build it
        echo "Building distribution for version $version"
        python ./djagitit/setup.py bdist_wheel
    fi
fi