#!/bin/bash
# Simple script for compiling/converting documents with pandoc because I can never remember how to use it

# Usage:
#   pandoc-make html *.md

usage() {
   SCRIPT="${0##*/}"
   cat <<-EOF
		Usage:
		   $SCRIPT [output_type]   [pandoc_args] [for] [file] [1] [file 1]    [pandoc_args] [for] [file] [2] [file 2]

		Examples:
		   $SCRIPT html README.md    # basic markdown to html
		   $SCRIPT .pdf *.tex        # leading .'s are automatically removed from the output file format
		   $SCRIPT .pdf \\
		      --pdf-engine pdflatex report.tex \\
		      --pdf-engine pdflatex README.md    # generates README.pdf and report.pdf with pdflatex

		Notes:
		   1) To put a file in pandoc arguments without having it be compiled to its
		      own document, put a './' or '../' at the start of the path to it
		     - You can have as many arg/file combinations you want
		     - The argument array is cleared between input files
	EOF
# TODO:
#		    2) You can set default arguments in the array PANDOC_DEFAULT_ARGS and export them for this script to use
}

confirm() {
   echo -n "$@"
   while true; do
      read -r YN
      case "$YN" in
         [Yy]) return 0 ;;
         *) return 1 ;;
      esac
   done
}

# Help menu (yes, I forget how to use my own programs sometimes)
if [[ -z "$1" ]]; then
   usage && exit 1
fi
if [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then
   usage && exit
fi

if [[ -z "$2" ]]; then
   echo "error: no files specified"
   usage && exit 1
fi

OUTPUT_FORMAT="$1"
SKIP=true  # don't process the first argument, it is the output format

for FILE in "$@";do
   $SKIP && SKIP=false && continue

   # PANDOC_ARGS="${PANDOC_DEFAULT_ARGS[*]:-"$PANDOC_ARGS"}"
   if [[ -f "$FILE" ]] && { [[ "${FILE:0:2}" != "./" ]] || [[ "${FILE:0:3}" != "../" ]]; }; then

      OUTPUT_FILE="${FILE%.*}.${OUTPUT_FORMAT##.}"

      # Guard against overwriting md files and tex files
      if { [[ "$OUTPUT_FORMAT" = md ]] || [[ "$OUTPUT_FORMAT" = tex ]]; } && [[ -f "$OUTPUT_FILE" ]]; then
         if confirm "Overwrite $FILE? [y/N]: "; then
            # Make new file names until there is no overwriting
            while [[ -f "$OUTPUT_FILE" ]]; do
               OUTPUT_FILE="${FILE%.*}-$((FILE_NUM++)).${OUTPUT_FORMAT##.}"
            done
            echo "Not overwriting, new name: '$OUTPUT_FILE'"

         else
            # Give some time to ctrl-c before overwrite…
            SLEEP_DURATION=1
            echo -n "'$FILE' will be overwritten in"
            for N in {3..1};do
               echo -n " $N"  && sleep $SLEEP_DURATION
            done
            echo
         fi
      fi

      pandoc "${PANDOC_ARGS[@]}" -o "$OUTPUT_FILE" "$FILE"
      PANDOC_ARGS=()

   else

      PANDOC_ARGS+=("$FILE")

   fi
done

# Error if no files were processed
if [ -z "$OUTPUT_FILE" ]; then
   echo "Error: no files to process were found" >&2
   exit 1
fi

# vim:et ts=3 sw=3