#!/bin/bash
#< Fully featured tips database - in bash

PROGNAME=`basename ${0}`
TIP_ROOT="/home/kevin/tipsdb"

if [ ! -d "${TIP_ROOT}" ]; then
  {
     echo "If this is the first time the script has been run"
     echo "you will need to define the TIP_ROOT variable"
     echo "and create the TIP_ROOT directory"
  } >&2
  exit 99
fi

usage() {
  {
      echo "Usage: ${PROGNAME} option"
      echo "   Where option is one of the following:"
      echo "   -list    List available tips"
      echo "   -add     Add tip to database"
      echo "   -edit    Edit an existing tip"
      echo "   -remove  Remove tip from database"
      echo "   -search  Query the database"
      echo "   -view    View a tip"
      echo "   -help    Display this usage message"
  } >&2
}

list_tips() {
  ls -1 ${TIP_ROOT} | sort -n | while read tip_id; do
     echo -n "${tip_id}: "
     tip_file="${TIP_ROOT}/${tip_id}/${tip_id}.tip"
     title=`sed -n '1 p' ${tip_file}`
     echo "${title}"
  done
}

edit_tip() {
  tput clear
  echo -n "Enter the Tip ID of the tip you want to modify: "
  read tip_id
  if [ -z "${tip_id}" ]; then
     echo "Error: No Tip ID entered" >&2
     exit 7
  fi
  tip_file="${TIP_ROOT}/${tip_id}/${tip_id}.tip"
  if [ ! -e "${tip_file}" ]; then
     echo "Error: ${tip_id} is not a valid Tip ID" >&2
     exit 8
  fi
  vi ${tip_file}
}

add_tip() {
  latest_tip=`ls -1 ${TIP_ROOT} | sort -n | sed -n '$ p'`
  # if tip directory empty, the next step will just result in
  # next_tip being set to 1
  (( next_tip = latest_tip + 1 ))
  tput clear
  if [ -e "${next_tip}" ]; then
     echo "Problem with directory structure in ${TIP_ROOT} - Exiting" >&2
     exit 2
  fi
  echo "Adding new tip with Tip ID: ${next_tip} to Database"
  echo "=================================================================="
  echo "Fill in the fields below. Once all fields are completed"
  echo "the file will be created, and vi will be opened to edit"
  echo -e "the body of the tip.\n"
  echo -n "Title: "
  read title
  echo -n "Category: "
  read category
  echo -n "Sub Category: "
  read sub_category
  date_added=`date +"%d/%m/%Y"`
  echo "Date Added: ${date_added}"
  author=`whoami`
  echo "Author: ${author}"
  echo -n "Is the above information correct? (y|n) [y]: "
  read response
  if [ -n "${response}" ]; then
     case ${response} in
        "y") # do nothing
             ;;
        "n") echo "Tip creation aborted" && exit 0
             ;;
        *)   echo "Invalid response: Tip creation aborted" >&2
             exit 4
             ;;
     esac
  fi
  # we've already checked for the existence of the target tips file
  # above... so we can now just go ahead and create it
  target_dir="${TIP_ROOT}/${next_tip}"
  target_file="${target_dir}/${next_tip}.tip"
  echo "-> Creating target directory: ${target_dir}"
  mkdir -p ${target_dir}
  if [ "$?" -eq "0" ]; then
     echo "<- Directory successfully created"
  else
     echo "<- Error during directory creation - Aborting" >&2
     exit 5
  fi
  echo "-> Creating target file: ${target_file}"
  touch ${target_file}
  if [ "$?" -eq "0" ]; then
     echo "<- Empty file successfully created"
  else
     echo "<- Error during file creation - Aborting" >&2
     exit 6
  fi
  echo "-> Populating target file: ${target_file}"
  {
     echo "${title}"
     echo "${category}"
     echo "${sub_category}"
     echo "${date_added}"
     echo -e "${author}\n"
  } > ${target_file}
  echo "<- Target file populated"
  echo "vi will now be executed to modify the tip file and add the"
  echo "main tip content. Remember to save and exit when done (:wq)"
  echo "Hit return to continue...."
  read dummy
  # User just has to hit "i" and start inserting the tip body
  vi +6j ${target_file}
}

remove_tip() {
  # This will just remove a tip - it will not attempt to renumber
  # existing tips. Therefore, there'll be gaps in tip IDs. If you
  # remove the last tip, however, the tip ID will be reused.
  tput clear
  echo -n "Enter the Tip ID of the tip you want to remove: "
  read tip_id
  if [ -z "${tip_id}" ]; then
     echo "Error: No Tip ID entered" >&2
     exit 7
  fi
  tip_file="${TIP_ROOT}/${tip_id}/${tip_id}.tip"
  if [ ! -e "${tip_file}" ]; then
     echo "Error: ${tip_id} is not a valid Tip ID" >&2
     exit 8
  fi
  title=`sed -n '1 p' ${tip_file}`
  echo "You have selected the following tip for removal:"
  echo "${tip_id} - ${title}"
  echo -n "Are you sure you want to remove this tip? (y|n) [n]: "
  read response
  if [ -n "${response}" ]; then
    case ${response} in
       "y") # do nothing
            ;;
       "n") echo "Tip removal aborted" && exit 0
            ;;
       *)   echo "Invalid response: Tip creation aborted" >&2
            exit 9
            ;;
    esac
  else
     # blank response - default n
     echo "Tip creation aborted" && exit 0
  fi
  echo "-> Removing Tip ID ${tip_id} from the Database"
  rm -r ${TIP_ROOT}/${tip_id}
  if [ "$?" -eq "0" ]; then
     echo "<- Tip ID ${tip_id} successfully removed"
  else
     echo "<- Error occurred trying to remove Tip ID ${tip_id}" >&2
     exit 10
  fi
}

view_tip() {
  tput clear
  echo -n "Enter the Tip ID of the tip you want to view: "
  read tip_id
  if [ -z "${tip_id}" ]; then
     echo "Error: No Tip ID entered" >&2
     exit 7
  fi
  tip_file="${TIP_ROOT}/${tip_id}/${tip_id}.tip"
  if [ ! -e "${tip_file}" ]; then
     echo "Error: ${tip_id} is not a valid Tip ID" >&2
     exit 8
  fi
  tput clear
  echo "================================================================"
  echo "Tip Information:"
  echo "================================================================"
  counter=0
  sed -n '1,5 p' ${tip_file} | while read line; do
     (( counter = counter + 1 ))
     case ${counter} in
        "1") echo "Title: ${line}" ;;
        "2") echo "Category: ${line}" ;;
        "3") echo "Sub Category: ${line}" ;;
        "4") echo "Date Added: ${line}" ;;
        "5") echo "Author: ${line}" ;;
     esac
  done
  echo "================================================================"
  echo "Hit return to view tip"
  echo "================================================================"
  read dummy
  sed -n '6,$ p' ${tip_file} | more
}

search_tips() {
  tput clear
  echo -n "Enter your search term: "
  read searchterm
  echo -n "Is this a case sensitive search? (y|n) [y]: "
  read searchtype
  if [ -z "${searchtype}" ]; then
     searchtype="y"
  fi
  case "${searchtype}" in
     "y") grep_options=""   ;;
     "n") grep_options="-i" ;;
     *)   echo "Warning: Input not recognised. Case sensitivity assumed" ;;
  esac
  ls -1 ${TIP_ROOT} | sort -n | while read tip_id; do
     tip_file="${TIP_ROOT}/${tip_id}/${tip_id}.tip"
     grep ${grep_options} "${searchterm}" ${tip_file} /dev/null |\
        sed 's!^.*/\([0-9][0-9]*\).tip:\(.*\)$!Tip ID \1: \2!'
  done
}

if [ "$#" -ne "1" ]; then
  usage && exit 1
fi

case "$1" in
 "-list")    list_tips ;;
 "-add")     add_tip ;;
 "-edit")    edit_tip ;;
 "-remove")  remove_tip ;;
 "-search")  search_tips ;;
 "-view" )   view_tip ;;
 "-help")    usage && exit 0 ;;
 *)          usage && exit 1 ;;
esac

exit 0