#!/usr/bin/env bash
# -----------------------------------------------------------------------------
#  Manthana (manthanaview.com) – one-shot install
#
#  Run from the project root on the server (or inside the Docker app container):
#      bash scripts/setup.sh
#
#  What it does:
#   1. creates .env (with fresh salts) if missing
#   2. composer install  (WordPress core, Bedrock packages, WooCommerce, WP-CLI)
#   3. installs WordPress, sets title / tagline / timezone / permalinks
#   4. activates the Manthana child theme + all bundled tagDiv plugins
#   5. uploads the Manthana site icon and applies logo / favicon settings
#   6. imports the Newspaper PRO demo if the theme license is already active,
#      otherwise prints the two-step instructions
#  Safe to re-run.
# -----------------------------------------------------------------------------
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

say()  { printf '\n\033[1;34m==> %s\033[0m\n' "$*"; }
warn() { printf '\033[1;33m!!  %s\033[0m\n' "$*"; }
die()  { printf '\033[1;31mxx  %s\033[0m\n' "$*"; exit 1; }

command -v php >/dev/null      || die "PHP 8.1+ is required."
command -v composer >/dev/null || die "Composer is required (https://getcomposer.org)."

# --- 1. .env -----------------------------------------------------------------
if [[ ! -f .env ]]; then
  say "Creating .env from .env.example"
  cp .env.example .env
  warn "Edit .env (DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, WP_HOME) and re-run this script."
  NEED_EDIT=1
fi

if grep -q "generateme" .env; then
  say "Generating unique salts in .env"
  php -r '
    $f = ".env"; $s = file_get_contents($f);
    $s = preg_replace_callback("/=\x27generateme\x27/", function () {
      $c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#%^&*()-_[]{}<>~+=,.;:/?|";
      $k = ""; for ($i = 0; $i < 64; $i++) { $k .= $c[random_int(0, strlen($c) - 1)]; }
      return "=\x27" . $k . "\x27";
    }, $s);
    file_put_contents($f, $s);'
fi

[[ "${NEED_EDIT:-0}" == "1" ]] && exit 0

# read the install-only variables from .env
set -a; # shellcheck disable=SC1091
source <(grep -E '^(SITE_TITLE|SITE_TAGLINE|ADMIN_USER|ADMIN_EMAIL|ADMIN_PASSWORD|SITE_TIMEZONE|SITE_LOCALE|WITH_WOO|WP_HOME|WP_ENV)=' .env); set +a

# --- 2. Composer ----------------------------------------------------------------
say "Installing PHP dependencies (WordPress core, Bedrock, WooCommerce, WP-CLI)"
composer install --no-interaction --prefer-dist --optimize-autoloader

if command -v wp >/dev/null; then WP="wp"; else WP="$ROOT/vendor/bin/wp"; fi
[[ "$(id -u)" == "0" ]] && WP="$WP --allow-root"
wp() { $WP "$@"; }

# --- 3. WordPress ----------------------------------------------------------------
if ! wp db query "SELECT 1" >/dev/null 2>&1; then
  wp db create >/dev/null 2>&1 || warn "Could not verify/create the database with the mysql client – continuing (check DB_* in .env if the next step fails)."
fi

if ! wp core is-installed 2>/dev/null; then
  say "Installing WordPress for ${WP_HOME}"
  if [[ -z "${ADMIN_PASSWORD:-}" ]]; then
    ADMIN_PASSWORD="$(php -r 'echo bin2hex(random_bytes(10));')"
    GENERATED_PW=1
  fi
  wp core install \
    --url="$WP_HOME" \
    --title="${SITE_TITLE:-Manthana}" \
    --admin_user="${ADMIN_USER:-manthana_admin}" \
    --admin_password="$ADMIN_PASSWORD" \
    --admin_email="${ADMIN_EMAIL:-admin@manthanaview.com}" \
    --skip-email
else
  say "WordPress already installed – updating settings only"
fi

wp option update blogname        "${SITE_TITLE:-Manthana}"
wp option update blogdescription "${SITE_TAGLINE:-}"
wp option update timezone_string "${SITE_TIMEZONE:-Asia/Kolkata}"
wp option update date_format     "F j, Y"
wp option update time_format     "g:i a"
wp option update blog_public     "$([[ "${WP_ENV:-production}" == "production" ]] && echo 1 || echo 0)"
wp rewrite structure '/%postname%/' --hard

if [[ "${SITE_LOCALE:-en_US}" != "en_US" ]]; then
  say "Installing language pack: ${SITE_LOCALE}"
  wp language core install "$SITE_LOCALE" --activate || warn "Could not install language ${SITE_LOCALE}; continuing in English."
fi

# --- 4. Theme + plugins ------------------------------------------------------------
say "Activating the Manthana theme (child of Newspaper)"
wp theme activate manthana

say "Activating tagDiv plugins"
# tagDiv Composer must come first – every other tagDiv plugin depends on it
wp plugin activate td-composer
wp plugin activate td-cloud-library td-social-counter td-newsletter td-standard-pack td-mobile-plugin td-subscription revslider

if [[ "${WITH_WOO:-0}" == "1" ]]; then
  say "Activating WooCommerce + tagDiv Woo"
  wp plugin activate woocommerce td-woo
fi

# remove WordPress sample content & default themes noise
wp post delete 1 --force >/dev/null 2>&1 || true   # "Hello world!"
wp post delete 2 --force >/dev/null 2>&1 || true   # "Sample Page"
wp comment delete 1 --force >/dev/null 2>&1 || true

# --- 5. Branding --------------------------------------------------------------------
say "Applying Manthana logo, favicon and site icon"
ICON="web/app/themes/manthana/assets/brand/manthana-site-icon.png"
if [[ -z "$(wp option get site_icon 2>/dev/null | grep -E '^[1-9]' || true)" ]]; then
  ICON_ID="$(wp media import "$ICON" --title="Manthana site icon" --porcelain)"
  wp option update site_icon "$ICON_ID"
fi
wp manthana brand --force

# --- 6. Newspaper PRO demo -----------------------------------------------------------
say "Newspaper PRO demo content"
if wp --context=admin manthana status 2>/dev/null | grep -q "License: *registered"; then
  wp --context=admin manthana import-demo --demo=default_pro --yes
else
  cat <<EOF

  The theme license is not activated yet, so the Newspaper PRO demo can't be
  downloaded from tagDiv. Two steps:

    1. Log in to ${WP_HOME}/wp/wp-admin
       → Newspaper → Activate Theme → enter your Envato purchase code

    2. Back on the server, run:
         composer import-demo
       (or: wp --context=admin manthana import-demo --yes)

     You can also click "Install" on "Default PRO" under
     Newspaper → Pre-built Websites – the Manthana logo is applied
     automatically after the import either way.
EOF
fi

wp rewrite flush --hard
wp cache flush >/dev/null 2>&1 || true

say "Done."
echo "  Site:   ${WP_HOME}"
echo "  Admin:  ${WP_HOME}/wp/wp-admin   user: ${ADMIN_USER:-manthana_admin}"
[[ "${GENERATED_PW:-0}" == "1" ]] && echo "  Password (shown once, store it now): ${ADMIN_PASSWORD}"
