#!/usr/bin/bash

set -u
umask 0027

## ======================================================================

sqlite_db="${MAILMAN_WEB_SQLITE_DB-/opt/osstech/var/lib/mailman-web/data/mailman-web.sqlite}"
sqlite_history="${MAILMAN_WEB_SQLITE_HISTORY-/opt/osstech/var/cache/mailman-web/sqlite/history}"

sqlite="${MAILMAN_WEB_SQLITE_COMMAND-/usr/bin/sqlite3}"
sqlite_rc="${MAILMAN_WEB_SQLITE_RC-/opt/osstech/etc/mailman-web/sqliterc}"

tty_p=
if [[ -t 0 && -t 1 ]]; then
  tty_p="set"
  for arg in "$@"; do
    if [[ $arg == @(-batch|--batch) ]]; then
      tty_p=""
      break
    fi
  done
fi

sqlite_init() {
  echo '.output /dev/null'
  echo ".open $sqlite_db"
  ## FIXME: Read mailman.env and do PRAGMAs
  echo 'PRAGMA busy_timeout=10000;'  # milliseconds (10 seconds)
  echo 'PRAGMA foreign_keys=true;'
  echo 'PRAGMA journal_mode=WAL;'
  echo 'PRAGMA synchronous=NORMAL;'
  echo 'PRAGMA journal_size_limit=67108864;'  # bytes (64 MiB)
  echo 'PRAGMA mmap_size=134217728;'  # bytes (128 MiB)
  echo 'PRAGMA cache_size=2000;'  # pages (2000 pages * 4096 bytes (default page_size))
  echo 'PRAGMA temp_store=MEMORY;'
  echo '.output stdout'
  if [[ -n $tty_p ]]; then
    cat "$sqlite_rc"
  fi
}

sqlite_args=()
if [[ -z $tty_p ]]; then
  sqlite_args+=(-batch)
fi

## ======================================================================

export SQLITE_HISTORY="$sqlite_history"

exec "$sqlite" \
  -init <(sqlite_init) \
  "${sqlite_args[@]}" \
  "$@" \
;
