#!/usr/bin/env bash

set -o errexit

usage() {
  cat <<EOS
  $(basename "$0")
    a simple script to create/find/manipulate scripts in ~/bin

  flags:
    -d, --delete  - Delete script.
    -g, --grep    - Find scripts containing given search query.
    -m, --move    - Rename/move script.
    -p, --page    - Show files with less.
    -h, --help    - Display this message.
EOS
  exit 0
}

BIN_DIR="${HOME%/}/bin"

POSITIONAL=""
while [ "$#" -gt 0 ]; do
  key="$1"
  case ${key} in
    -d | --delete)
      rm "${BIN_DIR}/$2"
      exit 0
      ;;
    -m | --move)
      mv "${BIN_DIR}/$2" "${BIN_DIR}/$3"
      exit 0
      ;;
    -p | --page)
      less "${BIN_DIR}/$2"
      exit 0
      ;;
    -g | --grep)
      shift
      if cmd-exists rg; then
        rg "$@" "${BIN_DIR}"
      else
        grep -nirE "$@" "${BIN_DIR}"
      fi
      exit 0
      ;;
    -h | --help)
      usage
      ;;
    *) # unknown option
      # save it in an array for later
      # POSITIONAL+=("$1")
      usage
      # past argument
      # shift
      ;;
  esac
done
# restore positional parameters
set -- "${POSITIONAL}"

# shellcheck disable=SC2012
[ -n "$1" ] && SCRIPTNAME="$1" || SCRIPTNAME=$(ls "${BIN_DIR}" | fzf +m)

touch "${BIN_DIR}/${SCRIPTNAME}"
[ -x "${BIN_DIR}/${SCRIPTNAME}" ] || chmod +x "${BIN_DIR}/${SCRIPTNAME}"
"${EDITOR-}" "${BIN_DIR}/${SCRIPTNAME}"
# dot add "${BIN_DIR}/${SCRIPTNAME}"
