#!/usr/bin/env bash
source ~/.secret_variables.sh

# README: this script required bash 4+ (it uses associative arrays, which are supported since bash 4)
#       also search two lists, one is commands and the other is links

# defaults
verbose="False"

list_links()
{
echo "Available links:"
iter=1
for key in "${!links[@]}"; do
    echo "$iter. $key at (${links[$key]})"
    ((iter = iter+1))
done
}

list_players()
{
echo "Available command line players:"
iter=1
for key in "${!players[@]}"; do
    echo "$iter. $key at (${players[$key]})"
    ((iter = iter+1))
done
}

help()
{
   echo "sopen (special open) is a bash/shell script for Unix (incl. Mac) that opens a requested link name (which is a shortcut name defined by the user in the sopen executable file directly). "
   echo
   echo "Usage:\n> sopen <name>"
   echo "options:"
   echo "-h --help                    	Display this help."
   echo "-l --list                    	Display available links (add more by editing the script)."
   echo
}


function parse_params() {
    local param
    while [[ $# -gt 0 ]]; do
        param="$1"
        shift
        case $param in
            -h | --help)
                help;
                exit 0
                ;;
            -l | --list)
                list_links;
                exit 0
                ;;
            -V | --verbose) 
                verbose="True"
		;;
            *)
		case $last_arg in
		  *) 
			echo "parameter was provided: $param"
                        target=$param
			;;
		esac
		;;
        esac
    done
}

parse_params "$@"
if [ $verbose == "True" ]
then
    echo "-------"
    echo "verbose todo"
    echo "-------"
fi

echo "${links[$target]}"
STR="${links[$target]}"
SUB='>'
if [[ "$STR" == *"$SUB"* ]]; then
  STR2=$(echo "$STR" | sed 's/>//')
  #echo "eval:"
  #echo "$STR2"
  if [ "${STR2:0:2}" == "cd" ]; then #this is a strange necessary hack right now
    echo -e "Opening in a subshell with command: $STR2\nDo exit to quit this subshell and return here."
    bash -c "exec bash --init-file <(echo \"$STR2\")"
  else
    eval "$STR2" #this works for a command like bitwarden but not for cd? What? TODO
  fi
else
  echo "open:" 
  open "${links[$target]}"
fi
