#!/bin/bash

DISTRACKED_DIR="$HOME/.distracked"

init() {
    if [[ ! -e "$DISTRACKED_DIR" ]]; then mkdir "$DISTRACKED_DIR"; fi
    cd "$DISTRACKED_DIR"; if [[ ! -e "main" ]]; then touch "main"; fi
    # The rest of the script will assume that:
    # - We are in the configuration directory.
    # - There is at least one stack, called "main".
}

current_stack() {
    ls -t |head -n 1
}

stack_list() {
    echo -n '* '
    ls -t |cat
}

stack_head() {
    tail -n 1 "$*"
}

docstr() {
    true
}

do_subcmd() {
    subcmd="$1"
    shift

    init
    case "$subcmd" in
    "all"   ) docstr "display entire contents of all stacks";
              for f in $(ls -t); do echo -ne "\n-- $f --\n* "; tac "$f"; done;;
    "cat"   ) docstr "display entire contents of current stack";
              echo -ne "-- $(current_stack) --\n* " ; tac "$(current_stack)" ;;
    "edit"  ) docstr "open all stacks in text editor for bulk modification";
              ${VISUAL:-${EDITOR:-nano}} $(ls -t) ;;
    "head"  ) docstr "display top of stack";
              echo -n '* ' ; stack_head "$(current_stack)" ;;
    "heads"  ) docstr "display tops of all stacks";
              for f in $(ls -t); do echo -ne "\n-- $f --\n* "; stack_head "$f"; done;;
    "help"  ) docstr "display this message";
              return 1 ;;
    "ls"    ) docstr "list all stacks";
              stack_list ;;
    "pop"   ) docstr "remove top of stack";
              stack_head "$(current_stack)" > .yank
              sed -i.bak '$d' "$(current_stack)"; rm *.bak ;;
    "push"  ) docstr "add given (default: last popped) item at top of stack";
              item=${*:-$(cat .yank)}
              echo "$item" >> "$(current_stack)" ;;
    "rm"    ) docstr "delete given stack";
              rm "$*" ;;
    "switch") docstr "switch to given stack, creating it if necessary";
              touch "$1" ; stack_list ;;
    ""      ) echo -n '* ' ; stack_head "$(current_stack)" ;;
    *)
        # Unrecognized subcmd
        return 1
        ;;
    esac
    return 0
}

usage() {
    echo "usage: $0 [subcmd]"
    ((echo "subcmd: | behavior:"
    declare -f do_subcmd |\
        grep -B1 '\bdocstr\b' |\
        grep -o '".*"' |\
        grep -o '[^"]*' |\
        sed 'N;s/\n/ | /'
    ) | column -s '|' -t
    ) | sed 's/^/  /'
    exit 1
}

# Script entry point
do_subcmd "$@"
if [[ "$?" -ne 0 ]]
then
    usage
fi

