#!/usr/bin/env bash
# site/wp-update -- update WordPress core, plugins and themes with a snapshot
#
# Updates are the moment a site breaks, so a snapshot is always taken first and
# its path is printed even when everything succeeds.
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_wpupdate)"

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

if [ ! -f "$root/wp-config.php" ]; then
    ui_err "$(t wp_update_not_wp)"
    exit 2
fi
if [ ! -x /usr/local/bin/wp ]; then
    ui_err "$(t site_wp_nocli)"
    exit 1
fi

current=$(sudo -u "$user" /usr/local/bin/wp --path="$root" core version 2>/dev/null || echo '?')
ui_kv "$(t col_domain)" "$domain"
ui_kv "$(t wp_core_now)" "$current"
ui_blank

ui_info "1) $(t wp_update_minor)"
ui_info "2) $(t wp_update_all)"
ui_info "3) $(t wp_update_plugins_only)"
ui_info "0) $(t menu_back)"
ui_blank
printf '  %s: ' "$(t menu_prompt_short)"
read -r pick || exit 130
case $pick in
    0) exit 0 ;;
    1|2|3) ;;
    *) ui_err "$(t menu_invalid)"; exit 2 ;;
esac

ui_warn "$(t wp_update_warn)"
ui_confirm "$(t wp_update_confirm)" n || { ui_info "$(t pf_cancelled)"; exit 0; }

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-update-$domain")
[ -n "$snap" ] || { nv_fail 4502 "$(t site_backup_failed)"; nv_lock_release "site:$domain"; exit 1; }
ui_ok "$(t backup_safety_at "$snap")"

WP="sudo -u $user /usr/local/bin/wp --path=$root"
fails=0
case $pick in
    1)
        ui_step "$(t wp_update_minor)"
        $WP core update --minor 2>&1 | sed 's/^/    /'
        $WP core update-db 2>&1 | sed 's/^/    /'
        ;;
    2)
        ui_step "$(t wp_update_core)"
        $WP core update 2>&1 | sed 's/^/    /' || fails=$((fails + 1))
        $WP core update-db 2>&1 | sed 's/^/    /'
        ui_step "$(t wp_update_plugins)"
        $WP plugin update --all 2>&1 | sed 's/^/    /' || fails=$((fails + 1))
        ui_step "$(t wp_update_themes)"
        $WP theme update --all 2>&1 | sed 's/^/    /' || fails=$((fails + 1))
        ;;
    3)
        ui_step "$(t wp_update_plugins)"
        $WP plugin update --all 2>&1 | sed 's/^/    /' || fails=$((fails + 1))
        ;;
esac

after=$(sudo -u "$user" /usr/local/bin/wp --path="$root" core version 2>/dev/null || echo '?')
nv_trace wp-update "$domain $current -> $after snapshot=$snap"
nv_lock_release "site:$domain"

ui_blank
ui_kv "$(t wp_core_now)" "$after"
ui_kv "$(t backup_location)" "$snap"
if [ "$fails" -eq 0 ]; then
    ui_ok "$(t wp_update_ok)"
else
    ui_warn "$(t wp_update_partial "$fails")"
    ui_info "$(t wp_update_rollback_hint "$snap")"
fi
exit 0
