#!/usr/bin/env sh
set -eu

TODO_DIR="${TODO_DIR:-$HOME/.todo}"
TODO_FILE="$TODO_DIR/todo.txt"

list_items()
{
  if ! [ -s "$TODO_FILE" ]; then
    echo "todo.txt is empty."
  fi
  while IFS= read -r line
  do 
    echo "$line"
  done < "$TODO_FILE"
}

add_item()
{
  echo "$@" >> "$TODO_FILE"
  echo "Added: $*"
}

usage() { echo "to -[healv] <string>" 1>&2; exit; }
version() { echo "to 0.1.0" 1>&2; exit; }

if [ ! -f "$TODO_FILE" ]; then
  while :
  do
    printf "%s does not exist.\nWould you like to create it? [Y/n] " "$TODO_FILE"
    read -r CREATE 
    CREATE=${CREATE:-y}
    case $CREATE in
      Y|y)
        touch "$TODO_FILE"
        echo "Created $TODO_FILE"
        break
        ;;
      n)
        echo "Exiting without creating file!"
        exit
        ;;
      *)
        ;;
  esac
done
fi

while getopts 'hea:lv' opt; do
  opt=${opt:-l}
  case $opt in
    (h) usage;;
    (e) "$EDITOR" "$TODO_FILE";; 
    (a) add_item ${OPTARG};;
    (l) list_items;;
    (v) version;;
    (?) exit 1;;
  esac
done

if (( $OPTIND == 1 )); then
  list_items
fi


