#!/usr/bin/env bash
# =====================================================================
# LogShip template — step 4 (on an INSTANCE clone): set client/org identity
# ---------------------------------------------------------------------
# Renames the kept tenant so a new instance is not branded "LogYou":
#   * ad_client 1000000        -> name/value/description
#   * ad_org    1000000        -> name/value/description
#   * the org-linked c_bpartner (ad_org.c_bpartner_id, "LogYou GmbH")
#     -> name/value, and its address name
#   * /opt/erp-nuxt-frontend/.env COMPANYNAME (SOLUTIONNAME = product
#     brand "LogShip" is left alone on purpose)
# Then restarts iDempiere (cached names!) + the frontend, and prints a
# report of remaining "old name" occurrences (users/emails, warehouses,
# roles, printers) for manual touch-up in the app.
#
#   04-set-instance-identity.sh [--dry-run] "<ClientName>" ["<OrgName>"] ["<CompanyLegalName>"]
#
#   ClientName        e.g. "Acme"          (tenant name + search keys)
#   OrgName           default: ClientName  (org 1000000 display name)
#   CompanyLegalName  default: ClientName  (linked business partner name)
#   --dry-run         run all SQL, show the result, ROLL BACK, no restarts
#
# NEVER run on production — guarded. Do not run on the golden template
# itself (it should stay "LogYou"); run on clones of it.
# =====================================================================
set -euo pipefail

DRY=0
if [ "${1:-}" = "--dry-run" ]; then DRY=1; shift; fi
[ -n "${1:-}" ] || { echo "usage: $0 [--dry-run] \"<ClientName>\" [\"<OrgName>\"] [\"<CompanyLegalName>\"]" >&2; exit 1; }

CLIENT_NAME="$1"
ORG_NAME="${2:-$CLIENT_NAME}"
COMPANY_NAME="${3:-$CLIENT_NAME}"

# --- production guard -----------------------------------------------------
if hostname | grep -q '^logship-production$'; then
  echo "FATAL: hostname is logship-production — refusing to run." >&2; exit 1
fi
if ip -4 addr show 2>/dev/null | grep -q '192\.168\.12\.72/'; then
  echo "FATAL: this host holds 192.168.12.72 (production IP) — refusing to run." >&2; exit 1
fi

# SQL-escape single quotes
esc() { printf "%s" "$1" | sed "s/'/''/g"; }
C=$(esc "$CLIENT_NAME"); O=$(esc "$ORG_NAME"); P=$(esc "$COMPANY_NAME")

FINAL="COMMIT"
[ "$DRY" = "1" ] && FINAL="ROLLBACK" && echo ">>> DRY RUN — everything below is rolled back <<<"

sudo -u postgres psql -d idempiere -v ON_ERROR_STOP=1 <<SQL
BEGIN;
SET LOCAL search_path TO adempiere, public;

UPDATE ad_client
   SET name = '${C}', value = '${C}', description = '${C} (LogShip instance)'
 WHERE ad_client_id = 1000000;

UPDATE ad_org
   SET name = '${O}', value = '${O}', description = '${O}'
 WHERE ad_org_id = 1000000;

-- org-linked business partner ("LogYou GmbH" on the template)
UPDATE c_bpartner
   SET name = '${P}', value = '${P}'
 WHERE c_bpartner_id IN (SELECT c_bpartner_id FROM ad_org
                         WHERE ad_org_id = 1000000 AND c_bpartner_id IS NOT NULL);
UPDATE c_bpartner_location
   SET name = '${P}'
 WHERE c_bpartner_id IN (SELECT c_bpartner_id FROM ad_org
                         WHERE ad_org_id = 1000000 AND c_bpartner_id IS NOT NULL);

-- main warehouse is named after the org on the template
UPDATE m_warehouse
   SET name = '${O}'
 WHERE ad_client_id = 1000000 AND name = 'LogYou';

-- roles "logyou Admin" / "logyou User" -> "<ClientName> Admin" / "... User"
UPDATE ad_role
   SET name = regexp_replace(name, '^logyou', '${C}', 'i')
 WHERE ad_client_id = 1000000 AND name ILIKE 'logyou%';

SELECT 'ad_client' AS what, ad_client_id AS id, name, value FROM ad_client WHERE ad_client_id = 1000000
UNION ALL
SELECT 'ad_org', ad_org_id, name, value FROM ad_org WHERE ad_org_id = 1000000
UNION ALL
SELECT 'linked c_bpartner', b.c_bpartner_id, b.name, b.value
  FROM c_bpartner b JOIN ad_org o ON o.c_bpartner_id = b.c_bpartner_id AND o.ad_org_id = 1000000
UNION ALL
SELECT 'm_warehouse', m_warehouse_id, name, '' FROM m_warehouse WHERE ad_client_id = 1000000
UNION ALL
SELECT 'ad_role', ad_role_id, name, '' FROM ad_role WHERE ad_client_id = 1000000 AND name NOT ILIKE '%template%';

-- touch-up report: things still carrying the old branding (rename in-app if wanted)
SELECT 'REMAINS: ' || t.what AS what, t.id, t.name, '' AS value FROM (
  SELECT 'ad_user'     AS what, ad_user_id::text     AS id, name || COALESCE(' <'||email||'>','') AS name
    FROM ad_user     WHERE ad_client_id=1000000 AND (name ILIKE '%logyou%' OR email ILIKE '%logyou%')
  UNION ALL
  SELECT 'ad_role',     ad_role_id::text,     name FROM ad_role     WHERE ad_client_id=1000000 AND name ILIKE '%logyou%'
  UNION ALL
  SELECT 'm_warehouse', m_warehouse_id::text, name FROM m_warehouse WHERE ad_client_id=1000000 AND name ILIKE '%logyou%'
  UNION ALL
  SELECT 'c_bpartner',  c_bpartner_id::text,  name FROM c_bpartner  WHERE ad_client_id=1000000 AND name ILIKE '%logyou%'
  UNION ALL
  SELECT 'cust_printer', cust_printer_id::text, name FROM cust_printer WHERE ad_client_id=1000000 AND name ILIKE '%logyou%'
) t;

${FINAL};
SQL

if [ "$DRY" = "1" ]; then
  echo ">>> DRY RUN complete — nothing changed."
  exit 0
fi

# --- frontend branding ----------------------------------------------------
ENVF=/opt/erp-nuxt-frontend/.env
if [ -f "$ENVF" ] && grep -qE '^COMPANYNAME=' "$ENVF"; then
  sed -i "s|^COMPANYNAME=.*|COMPANYNAME='${COMPANY_NAME}'|" "$ENVF"
  echo "set COMPANYNAME='${COMPANY_NAME}' in $ENVF"
fi

# --- restarts (iDempiere caches client/org names) -------------------------
systemctl restart idempiere || service idempiere restart || true
pm2 restart erpfrontend --update-env >/dev/null 2>&1 || true
echo "DONE. iDempiere restarting (takes ~1 min). Check the REMAINS report above for manual touch-ups."
