#!/usr/bin/env bash
# site/theme -- list themes and switch the active one
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_theme)"

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"

$WP theme list --fields=name,status,version,update --format=table 2>/dev/null | sed 's/^/  /'
ui_blank

printf '  %s (0 = %s): ' "$(t theme_activate_q)" "$(t menu_back)"
read -r slug || exit 130
slug=$(nv_trim "$slug")
case $slug in ''|0) exit 0 ;; esac
nv_valid_ident "$slug" || { ui_err "$(t plug_bad_slug)"; exit 2; }

if $WP theme activate "$slug" >/dev/null 2>&1; then
    nv_trace wp-theme "$domain activate $slug"
    ui_ok "$(t theme_activated "$slug")"
else
    nv_fail 3504 "$(t theme_failed)"
    exit 1
fi
exit 0
