#!/usr/app/TurboShell/bin/bash
# A notepad: add TEXT, list, delete NUMBER. The notes are in notes.txt.
set -euo pipefail
file=notes.txt
touch "$file"
mapfile -t notes <"$file"

save() {
  if ((${#notes[@]})); then
    printf '%s\n' "${notes[@]}" >"$file"
  else
    : >"$file"
  fi
}

case ${1:-} in
  add)
    text=${2:-}
    if [[ -z $text ]]; then
      echo "Nothing added: give a text"
      exit 1
    fi
    notes+=("${text//$'\n'/ }")
    save
    echo "Added note ${#notes[@]}"
    ;;
  list)
    ((${#notes[@]})) || echo "No notes"
    for i in "${!notes[@]}"; do
      echo "$((i + 1)). ${notes[i]}"
    done
    ;;
  delete)
    number=${2:-0}
    if [[ ! $number =~ ^[1-9][0-9]{0,5}$ ]] || ((number > ${#notes[@]})); then
      echo "There is no such note"
      exit 1
    fi
    unset 'notes[number - 1]'
    save
    echo "Deleted note $number"
    ;;
  *)
    echo "usage: add TEXT | list | delete NUMBER"
    exit 2
    ;;
esac
