#!/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

name=nvimpager
mode=auto
rc=${XDG_CONFIG_HOME:-~/.config}/nvimpager/init.lua
nvim=${NVIMPAGER_NVIM:-nvim}

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

	$name 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=0.11.0
      echo "$name ${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

if [[ -r $rc && -r ${rc%lua}vim ]] ; then
  echo Conflicting configs: "$rc" "${rc%lua}vim"
  exit 2
elif [[ ! -r $rc && -r ${rc%lua}vim ]]; then
  rc=${rc%lua}vim
elif [[ ! -r $rc ]]; then
  rc=NORC
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=()
stdin=false
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
args1=(
  -R
  ${rc:+-u "$rc"}
  --cmd 'set rtp+=$RUNTIME | lua nvimpager = require("nvimpager")'
)
# these come after all user supplied -c and --cmd arguments
args2=(
  --cmd 'lua 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
  args1+=(--headless)
fi
exec -a nvimpager $nvim "${args1[@]}" "${files[@]}" "$@" "${args2[@]}"
