#!/usr/bin/env bash

#############################################################################
# DESCRIPTION
#   A local shell script CLI container
#   - Features namespaced functions
#
# INSTRUCTIONS
#   - Run the following in your shell to enable/update functions
#       . ./devutils
#
#   - In terminal, type dev. with a dot hit tab key for autocomplete
#
#############################################################################

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" > /dev/null && pwd)"

# ----------------------------------------------------------------------- #
# confirm()
# Simple confirmation prompt before running something
# ----------------------------------------------------------------------- #
confirm() {
    question="Are you sure?"
    if [[ $# -eq 1 ]]; then
        question="${1}"
    fi
    read -p "${question} (y/[n]) " -n 1 -r answer
    echo -e '\n'
    if [[ ${answer} =~ ^[Yy]$ ]]; then
        echo 1
    else
        echo 0
    fi
}

# ----------------------------------------------------------------------- #
# get_colors()
# This function simply adds the echo color helpers for use in the script
# ----------------------------------------------------------------------- #
function get_colors() {
    case $SHELL in
        */bash) EXT='bash' ;;
        */fish) EXT='fish' ;;
        */zsh) EXT='zsh' ;;
        *) EXT='bash' ;;
    esac
    COLORS="bin/colors/ColorEcho.${EXT}"
    source ${COLORS}
}

# ----------------------------------------------------------------------- #
# dev.freezeup()
# Updates the requirements.txt file using compatible versions as
# specified in the requirements/base.pip file.
#
# USAGE
#   . ./devutils && dev.freezeup [-y]
#
#   -y  accept initial confirmation request without input
#
# A temporary virtual env is created so as not to affect any existing env
# that may include dev/test related packages.
# ----------------------------------------------------------------------- #
dev.freezeup() {
    echo -e "This script will update the frozen requirements file if any package updates exist."

    # Configuration Variables
    tempenv="tempvenv"
    flexible_reqs="requirements/base.pip"
    frozen_reqs="requirements.txt"
    pip_conf="pip.conf"

    if [[ "$1" =~ ^\-[Yy]$  ]]; then
        sure=1
    else
        # Confirm user wants to continue
        sure=$(confirm "Would you like to continue?")
    fi

    if [[ ${sure} -eq 0 ]]; then
        echo.Orange '\nAborted by user.'
        return 0
    fi

    echo.Blue "\n\nRunning freezeup ☃️"
    rm -rf "${tempenv}"
    echo.Yellow "\nInstalling/updating pip, wheel, setuptools"
    pip3 install -U pip wheel setuptools

    echo.Yellow "\nCreating temporary virtual env in ${tempenv}"
    python3 -m venv "${tempenv}" && . "${tempenv}/bin/activate"
    cp ./${pip_conf} ${tempenv}/
    pip install -U pip

    echo.Yellow "\nInstalling requirements"
    pip install -r "${flexible_reqs}"
    installed=$?
    if [[ ! ${installed} -eq 0 ]]; then
      echo.Red "Failed to install dependencies"
      echo "Removing temporary venv and aborting"
      rm -rf "${tempenv}"
      return 1
    fi

    echo.Yellow "\nChecking for any potential issues..."
    should_freeze=1
    pip_out=$(pip check)
    issues=$?
    if [[ ${issues} -eq 1 ]]; then
        echo.Orange "\nThere are potential conflicts with dependencies"
        echo.Red "${pip_out}\n"
        # todo: add option to fail --unattended
        should_freeze=$(confirm "Do you still want to update the frozen requirements file?")
    else
        echo -e "${pip_out}"
    fi

    updated=0
    if [[ ${should_freeze} -eq 1 ]]; then
        # cache the file contents in case of failure
        frozen_reqs_tmp="${frozen_reqs}.tmp"
        cp -f "${frozen_reqs}" "${frozen_reqs_tmp}"
        echo.Yellow "\nUpdating ${frozen_reqs} file..."
        pip freeze --exclude-editable > "${frozen_reqs}"
        update_failed=$?
        if [[ ${update_failed} -eq 1 ]]; then
            echo.Red " Ⓧ Failed! File ${frozen_reqs} not updated."
            mv -f "${frozen_reqs_tmp}" "${frozen_reqs}"
        else
            echo.Yellow " ✓ Success. ${frozen_reqs} updated."
            rm -f "${frozen_reqs_tmp}"
            updated=1
        fi
    else
        echo.Orange "\nNot updating ${frozen_reqs}. Aborted by user."
    fi

    echo.Yellow "\nCleaning up..."
    echo.Yellow " ✓ Deactivating virtual env"
    deactivate
    echo.Yellow " ✓ Removing temporary virtual env directory recursively"
    rm -rf "${tempenv}"
    echo.LightBlue "\nFinished."
}

get_colors
$*
