#!/bin/bash

# Copyright Security Onion Solutions LLC and/or licensed to Security Onion Solutions LLC under one
# or more contributor license agreements. Licensed under the Elastic License 2.0 as shown at
# https://securityonion.net/license; you may not use this file except in compliance with the
# Elastic License 2.0.

. /usr/sbin/so-common

usage() {
    echo "Usage: $0 <operation> [args]"
    echo ""
    echo "Supported Operations:"
    echo "  sql          Execute a SQL command, requires: <sql>"
    echo "  sqlfile      Execute a SQL file, requires: <path>"
    echo "  shell        Open an interactive psql shell"
    echo "  dblist       List databases"
    echo "  userlist     List database roles"
    echo ""
    exit 1
}

if [ $# -lt 1 ]; then
  usage
fi

# Check for prerequisites
if [ "$(id -u)" -ne 0 ]; then
    echo "This script must be run using sudo!"
    exit 1
fi

COMMAND=$(basename $0)
OP=$1
shift

set -eo pipefail

log() {
  echo -e "$(date) | $COMMAND | $@" >&2
}

so_psql() {
  docker exec so-postgres psql -U postgres -d securityonion "$@"
}

case "$OP" in

  sql)
    [ $# -lt 1 ] && usage
    so_psql -c "$1"
    ;;

  sqlfile)
    [ $# -ne 1 ] && usage
    if [ ! -f "$1" ]; then
      log "File not found: $1"
      exit 1
    fi
    docker cp "$1" so-postgres:/tmp/sqlfile.sql
    docker exec so-postgres psql -U postgres -d securityonion -f /tmp/sqlfile.sql
    docker exec so-postgres rm -f /tmp/sqlfile.sql
    ;;

  shell)
    docker exec -it so-postgres psql -U postgres -d securityonion
    ;;

  dblist)
    so_psql -c "\l"
    ;;

  userlist)
    so_psql -c "\du"
    ;;

  *)
    usage
    ;;
esac
