#!/bin/bash

# Checking if we are sourced
# see: https://stackoverflow.com/questions/2683279/how-to-detect-if-a-script-is-being-sourced
([[ -n $ZSH_EVAL_CONTEXT && $ZSH_EVAL_CONTEXT =~ :file$ ]] || 
[[ -n $BASH_VERSION ]] && (return 0 2>/dev/null)) && sourced=0 || sourced=1

# If goto is not run in sourced mode, it is not setup properly yet
if [[ $sourced -eq 1 ]]; then
    echo "Ah Hoy!"
    echo 
    echo "In order to make goto work properly, run this command now:"
    echo
    echo "       install_goto"
    echo
    exit 1
fi



PROJECT=$(cat ${HOME}/.goto/active-project)
PROJECTFILE="${HOME}/.goto/projects/${PROJECT}.json"

# Special case 1 (goto cd <magicword>)
if [ "$1" = "cd" ]; then
	# hack to cd in this shell to the ouput of goto show <magicword>
	path=$(goto show "$2")
	cd "$path"
    return 0
fi


# Special case 2  (goto <magicword>)
if [ "$#" -eq 1 ]; then

    # if run like: goto <magicword> 
    path=$(goto show "$1")

    # if path is folder, cd to folder
    if [ -d "$path" ]; then
        cd "$path"
        return 0

    # if path is file, open file
    elif [ -f "$path" ]; then
        goto open "$1"
        return 0
    fi
fi

# General case
the_real_goto.py "$PROJECTFILE" "$@"
