#! /usr/bin/env nix-shell
#! nix-shell -i bash -p bash_5 -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/046f8835dcb9082beb75bb471c28c832e1b067b6.tar.gz

# if no arguments (just starting the shell) give the welcome message
export PROJECTR_ARGS="$@"
# the comments above^ are special
#   they tell the system to process this using nix-shell
#   specifically using the exact version of bash to use

#
# find and run all the startup scripts in alphabetical order
#
# this loop is so stupidly complicated because of many inherent-to-shell reasons, for example: https://stackoverflow.com/questions/13726764/while-loop-subshell-dilemma-in-bash
for_each_item_in="$PROJECTR_FOLDER/settings/automatic_setup_prep"
[ -z "$__NESTED_WHILE_COUNTER" ] && __NESTED_WHILE_COUNTER=0;__NESTED_WHILE_COUNTER="$((__NESTED_WHILE_COUNTER + 1))"; trap 'rm -rf "$__temp_var__temp_folder"' EXIT; __temp_var__temp_folder="$(mktemp -d)"; mkfifo "$__temp_var__temp_folder/pipe_for_while_$__NESTED_WHILE_COUNTER"; (find -L "$for_each_item_in" ! -path . -print0 2>/dev/null | sort -z > "$__temp_var__temp_folder/pipe_for_while_$__NESTED_WHILE_COUNTER" &); while read -d $'\0' each
do
    # make sure its a each
    if [ -f "$each" ]; then
        if [ "$DEBUG_PROJECTR" = "true" ]
        then
            echo "loading: $each"
        fi
        source "$each"
    fi
done < "$__temp_var__temp_folder/pipe_for_while_$__NESTED_WHILE_COUNTER";__NESTED_WHILE_COUNTER="$((__NESTED_WHILE_COUNTER - 1))"

# create a dummy home folder to prevent any problems when starting up
__dummy_home="$PROJECTR_FOLDER/settings/.cache/home/"
rm -rf "$__dummy_home" > /dev/null
mkdir -p "$__dummy_home/.cache/"
# connect the nix cache to prevent duplicates
# check if file exists
if ! [ -d "$__dummy_home/.cache/nix" ]
then
    ln -s "$HOME/.cache/nix" "$__dummy_home/.cache/nix" 
fi

# if there are arguments, treat it as a run command
if [[ -n "$PROJECTR_ARGS" ]]
then
    # FIXME: I think the single quotes need to be escaped from the arguments
    # run single command
    HOME="$__dummy_home" nix-shell --pure --run "zsh -c '$PROJECTR_ARGS'" "$PROJECTR_FOLDER/settings/requirements/shell.nix"
else
    echo "=============================="
    echo " Setting up your Environment!"
    echo "=============================="
    HOME="$__dummy_home" nix-shell --pure --command "zsh" "$PROJECTR_FOLDER/settings/requirements/shell.nix"
fi