#!/usr/bin/bash

set -u
umask 0027

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

sqlite_db="${MAILMAN_SQLITE_DB-/opt/osstech/var/lib/mailman/data/mailman.sqlite}"

sqlite="${MAILMAN_SQLITE_COMMAND-/usr/bin/sqlite3}"
sqlite_rc="${MAILMAN_SQLITE_RC-/opt/osstech/etc/mailman/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 ".open $sqlite_db"
  echo 'PRAGMA foreign_keys=true;'
  if [[ -n $tty_p ]]; then
    cat "$sqlite_rc"
  fi
}

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

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

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