#!/bin/sh
#
# save - saves stdin into FILE; flags tells what to do when FILE exists.
# dependencies: ifne(1) and sponge(1) (moreutils)
#
# Usage: CMD | save [-abfin] FILE

# © 2025 Lucas de Sena <lucas at seninha dot org>.  No rights reserved.
# THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY (Works On My Machine™)

usage() {
  printf "usage: %s [-abfin] file\n" "${0##*/}" >&2
  exit 2
}

msg() {
  printf '%s' "$@" >&2
}

warn() {
  fmt="$1"
  shift
  msg "%s: ${fmt}\n" "${0##*/}" "$@"
}

err() {
  warn "$@"
  exit 1
}

unique() (
  basename="${1##*/}"
  dirname="${1%"${basename}"}"
  body="${basename%.*}"
  ext="${basename##"${body}"}"
  unset -v i p
  while test -e "${dirname}${body}${p}${i}${ext}"; do
    p="_"
    if test -z "${i}"; then
      i=1
    else
      i="$((i + 1))"
    fi
  done
  printf '%s' "${dirname}${body}${p}${i}${ext}"
)

if test "$#" -eq 3 && test "$2" = "--"; then
  # called as `save -opt -- file`
  set --"$1" "$3"
fi

case "$#" in
  2)
    case "$1" in
      -a | -append) action=a ;;
      -b | -backup) action=b ;;
      -f | -force | -overwrite) action=f ;;
      -i | -inter | -interactive | -ask) action=i ;;
      -n | -new) action=n ;;
      *) usage ;;
    esac
    file="$2"
    ;;
  1)
    action=
    file="$1"
    ;;
  *)
    usage
    ;;
esac

# shellcheck disable=SC2249
case "${file}" in
  ""|[[:space:]]*|*[[:space:]]) err "%s: Invalid argument" "${file}" ;;
esac

if test -d "${file}"; then
  err "%s: Is a directory" "${file}"
elif ! test -f "${file}"; then
  action=f
elif test -z "${action}"; then
  err "%s: File exists" "${file}"
elif test "${action}" = "i"; then
  msg "%s: File exists\n" "${file}"
  while true; do
    msg "\t(B)ackup,"
    msg " (F)orce overwrite,"
    msg " (A)ppend,"
    msg " or save as (N)ew file? "
    read -r action </dev/tty
    case "${action}" in
      [abfn])
        break
        ;;
      "")
        continue
        ;;
      *)
        msg "\tUnknown action\n"
        exit 1
        ;;
    esac
  done
fi

new="$(unique "${file}")"

cmd="sponge"
# shellcheck disable=SC2249
case "${action}" in
  a)
    # append into existing file
    cmd="sponge -a"
    ;;
  b)
    # backup existing file
    mv -f -- "${file}" "${new}" || exit
    ;;
  n)
    # save as new file, if exists
    file="${new}"
    ;;
esac
# shellcheck disable=SC2250
ifne "$cmd" -- "$file"
