#!/usr/bin/env bash
#
# Interactive shell.
#

# Load functions
LIB="`dirname $0`/../functions"
source "$LIB" maintenance $* || exit 1

# Basic parameters
SHELLPATH="/"

# Show usage
keyringer_usage $KEYRING

# While a "quit" command isn't entered, read STDIN
while read -rep "keyringer:/${KEYRING}${SHELLPATH}> " STDIN; do
  history -s "$STDIN"

  if [ "$STDIN" == "quit" ] || [ "$STDIN" == "exit" ] || [ "$STDIN" == "bye" ]; then
    break
  elif [ "$STDIN" == "shell" ]; then
    echo "Why you need nesting?"
  elif [[ "$STDIN" == "cd"* ]]; then

    # Update current path
    OLDPATH="$SHELLPATH"
    SHELLPATH="`echo $STDIN | sed -e 's/^cd//' | cut -d ' ' -f 2`"

    # Fix current path
    if [ "$SHELLPATH" == "/" ] || [ "$SHELLPATH" == "" ]; then
      SHELLPATH="/"
    elif [[ "$SHELLPATH" == ".."* ]]; then
      ARGS="$SHELLPATH"
      SHELLPATH="$OLDPATH"
      for colons in `echo $ARGS | sed -e 's|/| |g'`; do
        SHELLPATH="`dirname $SHELLPATH | sed -e 's|^\.||'`"
      done
    fi

    # Ensure path is absolute
    if echo "$SHELLPATH" | grep -v -q -e "^/"; then
      SHELLPATH="/$OLDPATH/$SHELLPATH"
    fi

    # Removing multiple slashes
    SHELLPATH="`echo $SHELLPATH | sed -e 's/\/\+/\//g'`"

    # Check if path exists
    if [ ! -d "$KEYDIR/$SHELLPATH" ]; then
      echo "No such folder $SHELLPATH"
      SHELLPATH="$OLDPATH"
    fi

  elif [[ -n "$STDIN" && "$STDIN" != "#"* ]]; then
    # If line is not empty or commented, process command
    RELATIVE_PATH="$SHELLPATH" keyringer "$KEYRING" $STDIN
  fi
done
