#!/usr/bin/env bash
# site/search-replace -- change a domain or string inside a WordPress database
#
# Always demonstrates the impact with a dry run, always snapshots first, and
# requires the domain to be typed back.
set -o pipefail
SELF=$(readlink -f "${BASH_SOURCE[0]}")
NV_BASE=$(cd "$(dirname "$SELF")/../../.." && pwd)
export NV_BASE
# shellcheck source=/dev/null
. "$NV_BASE/lib/core/bootstrap.sh"

nv_require_root || exit 1
ui_header "$(t site_m_searchreplace)"

site_pick_domain "${1:-}" || exit $?
domain=$SITE_DOMAIN
root=$(nv_site_get "$domain" root_path "$(site_domain_root "$domain")")
user=$(site_web_user "$domain")

[ -f "$root/wp-config.php" ] || { ui_err "$(t wp_update_not_wp)"; exit 2; }
[ -x /usr/local/bin/wp ] || { ui_err "$(t site_wp_nocli)"; exit 1; }

WP="sudo -u $user /usr/local/bin/wp --path=$root"
siteurl=$($WP option get siteurl 2>/dev/null || echo '')

ui_kv "$(t col_domain)" "$domain"
ui_kv "$(t wp_siteurl)" "${siteurl:--}"
ui_blank

printf '  %s [%s]: ' "$(t sr_from)" "$siteurl"
read -r from || exit 130
from=$(nv_trim "$from"); [ -z "$from" ] && from=$siteurl
[ -n "$from" ] || { ui_err "$(t sr_bad_input)"; exit 2; }

printf '  %s: ' "$(t sr_to)"
read -r to || exit 130
to=$(nv_trim "$to")
[ -n "$to" ] || { ui_err "$(t sr_bad_input)"; exit 2; }
[ "$from" = "$to" ] && { ui_info "$(t sr_same)"; exit 0; }

ui_blank
ui_step "$(t sr_dryrun)"
preview=$($WP search-replace "$from" "$to" --all-tables --dry-run --report-changed-only 2>&1 | tail -n 15)
printf '%s\n' "$preview" | sed 's/^/    /'

ui_blank
ui_warn "$(t sr_warn "$from" "$to")"
ui_confirm_typed "$(t sr_confirm)" "$domain" || { ui_info "$(t pf_cancelled)"; exit 3; }

nv_lock_acquire "site:$domain" 10 || { nv_fail 6199 "$(t lock_busy "$domain")"; exit 1; }

ui_step "$(t wp_update_snapshot)"
snap=$(site_snapshot "$domain" "pre-search-replace-$domain")
[ -n "$snap" ] || { nv_fail 4502 "$(t site_backup_failed)"; nv_lock_release "site:$domain"; exit 1; }
ui_ok "$(t backup_safety_at "$snap")"

ui_step "$(t sr_running)"
if $WP search-replace "$from" "$to" --all-tables --precise --report-changed-only 2>&1 | tail -n 15 | sed 's/^/    /'; then
    nv_trace search-replace "$domain $from -> $to snapshot=$snap"
    nv_lock_release "site:$domain"
    ui_ok "$(t sr_done)"
    ui_info "$(t sr_flush_hint)"
else
    nv_lock_release "site:$domain"
    ui_err "$(t sr_failed)"
    ui_info "$(t wp_update_rollback_hint "$snap")"
    exit 1
fi
exit 0
