#!/bin/bash -e

if [ -z "$1" ] || [[ "$1" == '--help' ]] || [[ "$1" == '-h' ]]; then
    echo "usage: $(basename $0) [--noterm] <file.pdf>" >&2
    exit 1
fi

if [[ "$1" == '--noterm' ]]; then
    term=false
    shift
else
    term=true
fi

infile="$1"

if [ ! -e "$infile" ] ;then
    echo "File not found: $infile" >&2
    exit 1
fi

# open the file with preferred application
nohup xdg-open "$infile" &>/dev/null &

cmd="
echo 'Xapers-adder'
echo '============'
echo 'Type C-c at any time to cancel...'
echo
while ! xapers add --file=\"$infile\" --tags=new --prompt --view; do
    read -N1 -p 'ENTER to try again, or C-c to quit:' OK
done
"

if [[ "$term" == 'true' ]] ; then
    exec x-terminal-emulator \
	-title "xapers-adder" \
	-e bash -c "$cmd"
else
    eval "$cmd"
fi
