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

if [ "${EUID}" -ne 0 ]; then
  echo "Run as root: sudo bash tools/db/install-db-setup.sh" >&2
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

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_DATABASE="${MYSQL_DATABASE:-photobooth}"
MYSQL_APP_USER="${MYSQL_APP_USER:-photobooth_app}"
MYSQL_APP_PASSWORD="${MYSQL_APP_PASSWORD:-}"

if [ -z "$MYSQL_ROOT_PASSWORD" ] || [ -z "$MYSQL_APP_PASSWORD" ]; then
  echo "Set MYSQL_ROOT_PASSWORD and MYSQL_APP_PASSWORD before running." >&2
  exit 1
fi

install -m 0755 "$SCRIPT_DIR/setup-db.sh" /usr/local/bin/photobooth-db-setup
install -m 0644 "$SCRIPT_DIR/photobooth-db.service" /etc/systemd/system/photobooth-db.service
install -m 0644 "$SCRIPT_DIR/photobooth-db.timer" /etc/systemd/system/photobooth-db.timer

cat > /etc/photobooth-db.env <<EOF
MYSQL_ROOT_USER=${MYSQL_ROOT_USER}
MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
MYSQL_HOST=${MYSQL_HOST}
MYSQL_PORT=${MYSQL_PORT}
MYSQL_DATABASE=${MYSQL_DATABASE}
MYSQL_APP_USER=${MYSQL_APP_USER}
MYSQL_APP_PASSWORD=${MYSQL_APP_PASSWORD}
EOF

chmod 600 /etc/photobooth-db.env

systemctl daemon-reload
systemctl enable --now photobooth-db.timer
systemctl start photobooth-db.service

echo "DB setup installed. It will run once and then stay idle."
