#!/usr/bin/env sh

# Description: Navigate to directory using jump/autojump/zoxide/z
#
# Dependencies:
#   - jump - https://github.com/gsamokovarov/jump
#   - OR autojump - https://github.com/wting/autojump
#   - OR zoxide - https://github.com/ajeetdsouza/zoxide
#   - OR z - https://github.com/rupa/z (z requires fzf)
#   - OR z (fish) - https://github.com/jethrokuan/z (z requires fzf)
#   - OR z.lua - https://github.com/skywind3000/z.lua (z.lua can enhanced with fzf)
#
# Note: The dependencies STORE NAVIGATION PATTERNS
#
# to make z.lua work, you need to set $NNN_ZLUA to the path of script z.lua
#
# Shell: POSIX compliant
# Authors: Marty Buchaus, Dave Snider, Tim Adler, Nick Waywood

if [ ! -p "$NNN_PIPE" ]; then
    printf 'ERROR: NNN_PIPE is not set!'
    read -r _
    exit 2
fi

if type jump >/dev/null 2>&1; then
    printf "jump to : "
    IFS= read -r line
    # shellcheck disable=SC2086
    odir="$(jump cd ${line})"
    printf "%s" "0c$odir" > "$NNN_PIPE"
elif type autojump >/dev/null 2>&1; then
    printf "jump to : "
    read -r dir
    odir="$(autojump "$dir")"
    printf "%s" "0c$odir" > "$NNN_PIPE"
elif type zoxide >/dev/null 2>&1; then
    if type fzf >/dev/null 2>&1; then
    	odir="$(zoxide query -i --)"
    	printf "%s" "0c$odir" > "$NNN_PIPE"
    else
	printf "jump to : "
    	read -r dir
    	odir="$(zoxide query -- "$dir")"
    	printf "%s" "0c$odir" > "$NNN_PIPE"
    fi
elif type lua >/dev/null 2>&1 && [ -n "$NNN_ZLUA" ]; then
    printf "jump to : "
    read -r line
    if type fzf >/dev/null 2>&1; then
        odir="$(lua "$NNN_ZLUA" -l "$line" | fzf --nth 2.. --reverse --inline-info --tac +s -e --height 35%)"
        printf "%s" "0c$(echo "$odir" | awk '{print $2}')" > "$NNN_PIPE"
    else
        odir="$(lua "$NNN_ZLUA" -e "$line")"
        printf "%s" "0c$odir" > "$NNN_PIPE"
    fi
else
    # rupa/z uses $_Z_DATA, jethrokuan/z (=port of z for fish) uses $Z_DATA
    datafile="${_Z_DATA:-${Z_DATA:-$HOME/.z}}"
    if type fzf >/dev/null 2>&1 && [ -f "$datafile" ]; then
        # Read the data from z's file instead of calling
        # z so the data doesn't need to be processed twice
        sel=$(awk -F "|" '{print $1}' "$datafile" | fzf | awk '{$1=$1};1')

        # NOTE: Uncomment this line and comment out the line above if
        # you want to see the weightings of the dir's in the fzf pane
        # sel=$(awk -F "|" '{printf "%s %s\n", $2, $1}' "$datafile" | fzf | sed 's/^[0-9,.]* *//' | awk '{$1=$1};1')

        printf "%s" "0c$sel" > "$NNN_PIPE"
    else
        printf "No supported autojump script [jump/autojump/zoxide/z (needs fzf)] found"
        read -r _
    fi
fi