#!/bin/bash

set -euo pipefail

# This script is only used for Lando.
# DDEV uses its own separate command at .ddev/commands/host/init-db (does not use init-db.sh).

# Lando-specific paths
DRUPAL_ROOT="/app/drupal"
DRUSH="${DRUPAL_ROOT}/vendor/bin/drush"
DUMP_FILE="${DRUPAL_ROOT}/dump/init.sql.gz"

# Verify required files exist
if [ ! -f "$DRUSH" ]; then
  echo "Error: Drush not found at ${DRUSH}"
  exit 1
fi

if [ ! -f "$DUMP_FILE" ]; then
  echo "Error: Dump file not found at ${DUMP_FILE}"
  exit 1
fi

# Prompt the user to confirm the action before proceeding. Answering anything but y will abort the script.
read -p "This will drop the current database and import the init.sql.gz dump. Are you sure you want to continue? (y/N) " -n 1 -r
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
  echo  # move to a new line
  echo "Skipping import... If the db is not already imported, you may need to run 'lando init-db' manually."
  exit 0
fi

# Remove the existing db.
echo "Dropping existing database..."
"$DRUSH" sql:drop -y

# Extract and import the dump.
echo "Importing init.sql.gz..."
gunzip -c "$DUMP_FILE" | "$DRUSH" sqlc

# Deploying
echo "Running drush deploy"
"$DRUSH" deploy

# Sanitize passwords only (keep emails unchanged)
echo "Sanitizing all passwords in the database..."
"$DRUSH" sql:sanitize --sanitize-email=no -y
echo "Password sanitization complete. All user passwords have been randomized."
