#!/bin/sh

# Inputs
bmdirs="$XDG_CONFIG_HOME/directories"

# Outputs
zsh_named_dirs="$ZDOTDIR/configs/hashes"
lf_dirs="$XDG_DATA_HOME/lf/dirs"

# TODO: Finish this function LOL
find_marker() {
    file=$1
    for marker in \
        "# @SHORTCUTS@" \
        "-- @SHORTCUTS@" \
        "// @SHORTCUTS@" \
        "/* @SHORTCUTS@ */"; do
        file=$(grep -xn "$marker" "$file")
        if [ -n "$file" ]; then
            echo "$file"
            return
        fi
    done
}

zsh() {
    xargs printf "hash -d %s=%s\n"
}

clean() {
    rm -rf "/tmp/shortcuts"
}

write_dirs_tmp() {
    mkdir -p /tmp/shortcuts
    while IFS= read -r line; do
        shortcut=$(echo "$line" | cut -d' ' -f1)
        path=$(echo "$line" | cut -d' ' -f2)
        path=$(eval "echo $path")

        printf "hash -d %s=%s\n" "$shortcut" "$path" >>"/tmp/shortcuts/zsh_named_dirs"
        printf "%\t%s\n" "$shortcut" "$path" >>"/tmp/shortcuts/lf_dirs"
    done
}

apply_tmp() {
    cat /tmp/shortcuts/zsh_named_dirs >"$zsh_named_dirs"
    cat /tmp/shortcuts/lf_dirs >"$lf_dirs"
}

read_file() {
    in_file=$1
    sed 's/#.*//;/^$/d' "$in_file" | tr -s ' '
}

trap clean EXIT

read_file "$bmdirs" | write_dirs_tmp

apply_tmp

clean