#!/usr/app/TurboShell/bin/bash
# Notatnik: add TEKST, list, delete NUMER. Notatki są w 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 "Nic nie dodano: podaj tekst"
      exit 1
    fi
    notes+=("${text//$'\n'/ }")
    save
    echo "Dodano notatkę ${#notes[@]}"
    ;;
  list)
    ((${#notes[@]})) || echo "Brak notatek"
    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 "Nie ma takiej notatki"
      exit 1
    fi
    unset 'notes[number - 1]'
    save
    echo "Usunięto notatkę $number"
    ;;
  *)
    echo "użycie: add TEKST | list | delete NUMER"
    exit 2
    ;;
esac
