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

MYSQL_ROOT_USER="${MYSQL_ROOT_USER:-root}"
MYSQL_ROOT_PASSWORD="${MYSQL_ROOT_PASSWORD:-}"
MYSQL_HOST="${MYSQL_HOST:-127.0.0.1}"
MYSQL_PORT="${MYSQL_PORT:-3306}"
MYSQL_APP_PASSWORD="${MYSQL_APP_PASSWORD:-}"
MARKER_FILE="${MARKER_FILE:-/var/lib/photobooth/db-setup.done}"

if [ -z "$MYSQL_ROOT_PASSWORD" ] || [ -z "$MYSQL_APP_PASSWORD" ]; then
  echo "Error: MYSQL_ROOT_PASSWORD and MYSQL_APP_PASSWORD required" >&2
  exit 1
fi

if [ -f "$MARKER_FILE" ]; then
  echo "Database already initialized."
  exit 0
fi

mkdir -p "$(dirname "$MARKER_FILE")"

# Find mysql command
if ! command -v mysql &> /dev/null; then
  echo "Error: mysql not found in PATH" >&2
  exit 1
fi

# Create temp SQL file with actual password
TEMP_SQL=$(mktemp)
trap "rm -f $TEMP_SQL" EXIT

sed "s/photobooth_app_password_placeholder/$MYSQL_APP_PASSWORD/g" \
  "$(dirname "$0")/photobooth.sql" > "$TEMP_SQL"

# Execute
MYSQL_PWD="$MYSQL_ROOT_PASSWORD" mysql \
  -h "$MYSQL_HOST" \
  -P "$MYSQL_PORT" \
  -u "$MYSQL_ROOT_USER" < "$TEMP_SQL" || {
  echo "Error: Database setup failed" >&2
  exit 1
}

touch "$MARKER_FILE"
echo "Database setup completed."


