#!/usr/bin/env bash
existing_filepath="$1"
target_filepath="$2"

# 
# ensure FORNIX_FOLDER exists
# 
if [ -z "$FORNIX_FOLDER" ]
then
    # 
    # find fornix_core
    # 
    path_to_file=""
    file_name="settings/fornix_core"
    folder_to_look_in="$PWD"
    while :
    do
        # check if file exists
        if [ -f "$folder_to_look_in/$file_name" ]
        then
            path_to_file="$folder_to_look_in/$file_name"
            break
        else
            if [ "$folder_to_look_in" = "/" ]
            then
                break
            else
                folder_to_look_in="$(dirname "$folder_to_look_in")"
            fi
        fi
    done
    if [ -z "$path_to_file" ]
    then
        #
        # what to do if file never found
        #
        echo "Im a script running with a pwd of:$PWD"
        echo "Im looking for settings/fornix_core in a parent folder"
        echo "Im exiting now because I wasnt able to find it"
        echo "thats all the information I have"
        exit
    fi
    export FORNIX_NEXT_RUN_ONLY_DO_BASIC_INIT="true"
    # run the basic init of fornix to get the FORNIX_FOLDER/FORNIX_COMMANDS_FOLDER/FORNIX_HOME etc
    . "$path_to_file"
fi


# 
# make existing_filepath absolute
# 
case "$existing_filepath" in
    # if absolute
    /*) : ;;
    # if relative
    *) existing_filepath="$FORNIX_FOLDER/$existing_filepath" ;;
esac

# 
# make target_filepath absolute
# 
case "$target_filepath" in
    # if absolute
    /*) : ;;
    # if relative
    *) target_filepath="$FORNIX_FOLDER/$target_filepath" ;;
esac

# remove existing things in the way
rm -f "$target_filepath" 2>/dev/null
rm -rf "$target_filepath" 2>/dev/null
# make sure parent folder exists
mkdir -p "$(dirname "$target_filepath")"
__temp_var__relative_part="$(realpath "$(dirname "$existing_filepath")" --relative-to="$(dirname "$target_filepath")" --canonicalize-missing)"
__temp_var__relative_path="$__temp_var__relative_part/$(basename "$existing_filepath")"
# link using the relative path
if [ -d "$existing_filepath" ]
then
    ln -s "$__temp_var__relative_path/" "$target_filepath"
else
    ln -s "$__temp_var__relative_path" "$target_filepath"
fi
unset __temp_var__relative_path
unset __temp_var__relative_part
unset existing_filepath
unset target_filepath