#!/bin/sh -e
#
# csv2table - output csv fields as markdown table vs interactive with sqlite3

usage() {
  printf '%s\n' "Usage: ${0##*/} <csv_file> [-i <csv_file> [<table_name>]]"
}

interactive=0
while getopts ':hi' opt; do
  case "${opt}" in
    h)
      usage
      exit 0
      ;;
    i)
      interactive="true"
      ;;
    ?)
      printf "%s: Unrecognized option: '-%c'\n" "${0##*/}" "${OPTARG}" >&2
      exit 1
      ;;
    *)
      usage
      exit 1
      ;;
  esac
done
shift "$((OPTIND - 1))"

if [ "$#" -eq 0 ]; then
  usage
  exit 1
fi

csvfile="$1"
if [ ! -s "${csvfile}" ]; then
  printf '%s\n' "${0##*/}: missing or empty file ${csvfile}" >&2
  exit 1
fi

if [ "${interactive}" = "true" ]; then
  tablename="${csvfile%%\.csv}"
  [ -z "${tablename}" ] && echo "unable to determine tablename"
  if expr "X${tablename}" : 'X.-' >/dev/null; then
    # [ $tablename =~ [-] ]; then
    echo "tablename cannot contain hypen - converting to underscore (_)"
    tablename=$(echo "${tablename}" | tr "-" "_")
  fi

  echo "csv file  : ${csvfile}"
  echo "table name: ${tablename}"

  # shellcheck disable=SC2250
  sqlite3 -interactive \
    -cmd ".mode csv" \
    -cmd ".mode columns" \
    -cmd ".headers on" \
    -cmd ".import $csvfile '$tablename'"
else
  pandoc --from=csv --to=gfm "${csvfile}"
fi
