#! /usr/bin/env bash

watcher::run() {
  local LAST_DIR="$PWD"
  local HERE_DIR="$(dirname "$0")"
  local RET_VAL=0
  cd "$HERE_DIR"

  local VIABLE="$(find * -type d -name '*')"
  local VIABLE_PRETTY="$(\
    echo "$VIABLE" \
      | tr '\n' '|' \
      | sed -Ee 's/(.*)\|/<\1>/g')"
  local USAGE="$HERE_DIR $VIABLE_PRETTY"

  do_print_errc() {
    case $1 in
      0) ;;
      1) echo "$USAGE" ;;
      2) echo "$USAGE" ;;
      3) echo ' no container id found.'
         echo ' has the container been built?';;
      4) echo ' container id is empty.'
         echo ' was there an error building the container?';;
      5) echo ' container not found to be running.'
         echo ' was there an error building the container?';;
      6) echo ' could not attach to the container.'
         echo ' was there an error building the container?';;
      9) echo ' something bad and mysterious happened.';;
      *) echo ' something bad and mysterious happened.';;
    esac
  }

  if test $# -eq 1
  then
    if echo "$1" | grep -qE "$VIABLE"
    then
      if test -f "$1/.container_id"
      then
        CONTAINER_ID="$(cat "$1/.container_id")"
        CONTAINER_ID_SHORT="${CONTAINER_ID[@]:0:12}"
        if test -n "$CONTAINER_ID"
        then
          if docker ps --format='{{.ID}}' | grep -q "$CONTAINER_ID_SHORT"
          then
            if ! docker exec -it "$CONTAINER_ID" bash
            then
              do_print_errc 6
              RET_VAL=4
            else
              do_print_errc 0
              RET_VAL=0
            fi
          else
            do_print_errc 5
            RET_VAL=3
          fi
        else
          do_print_errc 4
          RET_VAL=2
        fi
      else
        do_print_errc 3
        RET_VAL=1
      fi
    else
      do_print_errc 2
      RET_VAL=1
    fi
  else
    do_print_errc 1
    RET_VAL=1
  fi
  cd "$LAST_DIR"
  return $RET_VAL
}

watcher::run $@
exit $?
