#!/bin/bash
#   Common utils for goto scripts in bash
#   
#########################################


function prompt {
    # Asks a y|n question and returns true or false.
    question="$1"
    read -p "$question" REPLY
    if [[ $REPLY =~ ^[Yy.*]$ ]]; then
        return 0
    else
        return 1
    fi
}


function check_status {
    # Checking exit status of prev cmd:
    # see  https://stackoverflow.com/questions/26675681/how-to-check-the-exit-status-using-an-if-statement-using-bash
    exit_status="$?"
    if [ $exit_status -ne 0 ]; then
        echo "ERROR: Installation step failed with exit code $exit_status"
        if [[ "$#" -ne 2 ]]; then # pass an argument to this and we won't exit
            exit $exit_status
        else
            return $exit_status
        fi
    fi
}

function load_gotopath {
    if [[ -z "$GOTOPATH" ]]; then
        GOTOPATH="${HOME}/.goto"
    fi
}

function create_goto_folders {
    FOLDER="$1"

    if [[ -z "$FOLDER" ]]; then
        echo "Fatal error: GOTOPATH is empty (install directory)"
        exit 1
    fi

    if [[ ! -d "$FOLDER" ]]; then
        mkdir "${FOLDER}" || check_status
        mkdir "${FOLDER}/projects" || check_status
        touch "${FOLDER}/active-project" || check_status

        echo "Created goto folder in '${FOLDER}'"
    fi
}


