# setup: Set up application for the first time after cloning, or set it
#        back to the initial first unused state.

# Load setup functions
source ./script/include/setup_functions.inc.sh

## Set option defaults
# If CREATE_VENV is not set, set it to "true"
if [ -z "${CREATE_VENV+is_set}" ]; then
  CREATE_VENV="true"
fi

# If INSTALL_SASS is not set, set it to "false"
if [ -z "${INSTALL_SASS+is_set}" ]; then
  INSTALL_SASS="false"
fi

# If PIP_VERSION is not set, set it to "10.*"
if [ -z "${PIP_VERSION+is_set}" ]; then
  PIP_VERSION="10.*"
fi

# If RESET_DB is not set, set it to "false"
if [ -z "${RESET_DB+is_set}" ]; then
  RESET_DB="false"
fi

# If KEEP_EXISTING_VENV is not set, set it to "false"
if [ -z "${KEEP_EXISTING_VENV+is_set}" ]; then
  KEEP_EXISTING_VENV="false"
fi

## Main
# Remove any existing node modules as part of initial app setup or reset
rm -rf ./node_modules

if [ "${CREATE_VENV}" = "true" ]; then
  # Ensure pipenv is installed
  if ! pipenv --version >/dev/null 2>&1 ; then
    echo "ERROR: pipenv is malfunctioning or not present"
    exit 1
  fi

  python_version=$(grep python_version ./Pipfile | cut -d '"' -f 2)
  if ! check_for_existing_virtual_environment "${python_version}" || \
       [ "${KEEP_EXISTING_VENV}" = "false" ]
  then
    create_virtual_environment "${python_version}"
  fi

  pip_install "pip==${PIP_VERSION}" "--upgrade"
fi

if [ "${INSTALL_SASS}" = "true" ]; then
  install_sass
fi

# Install application dependencies
./script/bootstrap

if [ "${RESET_DB}" = "true" ]; then
  # Fetch postgres settings and set them as ENV vars
  source ./script/get_db_settings

  if [ -n "${PGDATABASE}" ]; then
    echo "Resetting database ${PGDATABASE}..."
    # Reset the db
    reset_db "${PGDATABASE}"
  else
    echo "ERROR: RESET_DB is set, but PGDATABASE is not!"
    echo "Skipping database reset..."
  fi
fi
