#!/usr/bin/env bash

# Copyright (c) 2017 Lucas Hoffmann
# Licenced under a BSD-2-clause licence.  See the LICENSE file.

RUNTIME=${BASH_SOURCE%/*}
PARENT=$PPID
TMPFILE=
export RUNTIME
export PARENT
export TMPFILE
export NVIM_APPNAME=nvimpager

mode=auto
nvim=${NVIMPAGER_NVIM:-nvim}

usage () {
  echo "Usage: ${0##*/} [-acp] [--] [nvim options and files]"
  echo "       ${0##*/} -h"
  echo "       ${0##*/} -v"
}
description () {
  cat <<-EOF

	$NVIM_APPNAME provides a simple pager based on neovim.
	Options:
	  -h		this help
	  -v		version output
	  -a		enforce auto mode (default)
	  -c		enforce cat mode
	  -p		enforce pager mode

	All further arguments are passed to neovim.  But one has to add "--"
	if the first argument is an option in order to stop this script from
	interpeting it.

	If "-" or no files are given stdin is read.

	In auto mode, if the cumulative length of all file arguments is
	smaller than the terminal size, cat mode is used, otherwise pager mode
	is used.  If any none file argument (neovim option) is given pager
	mode is implied.
	EOF
}

while getopts achpv flag; do
  case $flag in
    a) mode=auto;;
    c) mode=cat;;
    h) usage; description; exit;;
    p) mode=pager;;
    v)
      version=$(git -C "$RUNTIME" describe 2>/dev/null) || version=0.13.0
      echo "$NVIM_APPNAME ${version#v}"
      exit
      ;;
    *) usage >&2; exit 2;;
  esac
done
shift $((OPTIND - 1))

# Display the usage text if no arguments where given and stdin is a tty.
if [[ $# -eq 0 && -t 0 ]]; then
  usage
  exit 2
fi

# If we are not on a tty just "be" cat.
if [[ ! -t 1 && $mode = auto ]]; then
  exec cat "$@"
fi

# Collect all file arguments until the first non file into $files.  If one non
# file is found pager mode is enforced.  The special "file"-name "-" is
# accepted as stdin.
files=()
while [[ $# -gt 0 ]]; do
  if [[ -f $1 ]]; then
    files+=("$1")
    shift
  elif [[ $1 = - ]]; then
    TMPFILE=$(mktemp)
    files+=("$TMPFILE")
    shift
  else
    if [[ $mode = auto ]]; then
      mode=pager
    fi
    break
  fi
done

# If we did not get any file arguments and stdin is not a terminal, read stdin
# into a temp file.
if [[ -z $TMPFILE && ${#files[@]} -eq 0 && ! -t 0 ]]; then
  TMPFILE=$(mktemp)
  files=("$TMPFILE")
fi
if [[ $TMPFILE ]]; then
  # Bash runs the EXIT trap also when exiting due to signals.
  trap 'rm -f "$TMPFILE"' EXIT
  cat > "$TMPFILE"
fi

# these come before all user supplied -c and --cmd arguments
args=(
  -R
  --cmd 'set rtp+=$RUNTIME | lua nvimpager = require("nvimpager"); nvimpager.stage1()'
  -c 'lua nvimpager.stage2()'
)
# Switch to cat mode if all files combined are shorter than the terminal
# height.
if [[ $mode = cat || \
      $mode = auto && $(cat "${files[@]}" | wc -l) -le $(tput lines) ]]
then
  args+=(--headless)
fi
exec -a nvimpager $nvim "${args[@]}" "${files[@]}" "$@"
