#!/usr/bin/env bash
set -euo pipefail

if (($# != 1)); then
  printf 'Usage: %s "SELECT ..."\n' "$0" >&2
  exit 64
fi

sql="$1"
trimmed="${sql#"${sql%%[![:space:]]*}"}"
if [[ -z "$trimmed" ]]; then
  printf 'Only read-only SQL is allowed.\n' >&2
  exit 64
fi
if [[ "$sql" == *\\* ]]; then
  printf 'MySQL client commands and backslash escapes are not allowed.\n' >&2
  exit 64
fi
if [[ "$trimmed" == *";"* && "${trimmed%;}" == *";"* ]]; then
  printf 'Multiple SQL statements are not allowed.\n' >&2
  exit 64
fi
if [[ "$trimmed" == *"/*"* || "$trimmed" == *"#"* || "$trimmed" =~ --[[:space:]] ]]; then
  printf 'SQL comments are not allowed.\n' >&2
  exit 64
fi

shopt -s nocasematch
if [[ ! "$trimmed" =~ ^(SELECT|SHOW|DESCRIBE|EXPLAIN)[[:space:]] ]]; then
  printf 'Only read-only SQL is allowed.\n' >&2
  exit 64
fi
if [[ "$trimmed" =~ INTO[[:space:]]+(OUTFILE|DUMPFILE) ]]; then
  printf 'SQL file writes are not allowed.\n' >&2
  exit 64
fi
shopt -u nocasematch

: "${WP_DB_HOST:?WP_DB_HOST is required.}"
: "${WP_DB_PORT:?WP_DB_PORT is required.}"
: "${WP_DB_NAME:?WP_DB_NAME is required.}"
: "${WP_DB_USER:?WP_DB_USER is required.}"
: "${WP_DB_PASSWORD:?WP_DB_PASSWORD is required.}"
: "${WP_DB_SSL_MODE:?WP_DB_SSL_MODE is required.}"
: "${WP_DB_SSL_CA:?WP_DB_SSL_CA is required.}"

if [[ "$WP_DB_SSL_MODE" != "VERIFY_IDENTITY" ]]; then
  printf 'WP_DB_SSL_MODE must be VERIFY_IDENTITY.\n' >&2
  exit 65
fi
if [[ ! -r "$WP_DB_SSL_CA" ]]; then
  printf 'WP_DB_SSL_CA must identify a readable CA certificate.\n' >&2
  exit 66
fi

MYSQL_PWD="$WP_DB_PASSWORD" mysql \
  --no-defaults \
  --no-login-paths \
  --host="$WP_DB_HOST" \
  --port="$WP_DB_PORT" \
  --user="$WP_DB_USER" \
  --database="$WP_DB_NAME" \
  --ssl-mode=VERIFY_IDENTITY \
  --ssl-ca="$WP_DB_SSL_CA" \
  --batch \
  --execute="$sql"
