#!/usr/bin/env bash
# Per clone: make a freshly cloned test store look like a small owner set it up with one email.
# Run inside the clone's document root after WP Toolkit's Clone finishes:
#   bash claim-store.sh someone@temp-mail-domain 'SomePassword1!'
# The email becomes the admin login, the site admin email, and every WooCommerce "from"/notice address.
set -euo pipefail
EMAIL="$1"; PASS="${2:-$(openssl rand -base64 12)}"
WP="wp --quiet"

$WP user create "$EMAIL" "$EMAIL" --role=administrator --user_pass="$PASS" --display_name="${EMAIL%%@*}"
NEW_ID=$($WP user get "$EMAIL" --field=ID)
# Remove the template's admin(s); their content moves to the new owner.
for id in $($WP user list --role=administrator --field=ID); do
  [ "$id" = "$NEW_ID" ] || $WP user delete "$id" --reassign="$NEW_ID" --yes
done

for opt in admin_email new_admin_email woocommerce_email_from_address woocommerce_stock_email_recipient; do
  $WP option update "$opt" "$EMAIL"
done
$WP option delete adminhash 2>/dev/null || true

# WooCommerce Subscriptions treats a cloned site as staging and turns renewals manual; mark this one live.
$WP plugin is-active woocommerce-subscriptions && $WP eval 'WCS_Staging::set_duplicate_site_url_lock();'

# Clear anything the template had queued so it doesn't fire against this site.
$WP action-scheduler clean --status=pending,past-due 2>/dev/null || true
$WP cache flush; $WP transient delete --all

echo "Owner: $EMAIL  Password: $PASS  Login: $($WP option get siteurl)/wp-admin"

