#!/bin/bash
# HonorPro broker setup — one shot, Ubuntu 22.04+.
#
#   curl -fsSL https://files.zigzagtrader.com/honorpro-setup.sh | sudo bash -s -- \
#       --hub https://hub.zigzagtrader.com --enroll <ENROLLMENT_TOKEN>
#
# Installs and starts the whole broker side:
#   /opt/honorpro/gateway   the API service the terminal talks to (port 8120)
#   /opt/honorpro/agent     the Hub Agent (outbound-only daemon)
# DEFAULT CREDENTIALS ARE CONSTANT AND DOCUMENTED — see the Broker Setup Guide.
# Change them immediately after install (the guide shows how):
#   gateway admin console:  admin / HonorPro2026!
#   gateway<->agent token:  hp-outbox-2026
set -euo pipefail

HUB=""; ENROLL=""
while [ $# -gt 0 ]; do
  case "$1" in
    --hub) HUB="$2"; shift 2;;
    --enroll) ENROLL="$2"; shift 2;;
    *) echo "unknown arg $1"; exit 2;;
  esac
done
[ -n "$HUB" ] && [ -n "$ENROLL" ] || { echo "usage: honorpro-setup.sh --hub <URL> --enroll <TOKEN>"; exit 2; }
HUB="${HUB%/}"

echo "== HonorPro broker setup =="
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq && apt-get install -yqq python3-venv python3-pip curl >/dev/null

mkdir -p /opt/honorpro/agent /opt/honorpro/gateway
cd /opt/honorpro

echo "-- downloading packages from the hub --"
curl -fsS "$HUB/api/setup/download/honorpro-gateway.tar.gz?token=$ENROLL" -o gateway.tar.gz
curl -fsS "$HUB/api/setup/download/hub-agent.py?token=$ENROLL" -o agent/hub_agent.py
tar -xzf gateway.tar.gz -C gateway --strip-components=0 && rm gateway.tar.gz

echo "-- python environment --"
python3 -m venv venv
./venv/bin/pip -q install --upgrade pip
./venv/bin/pip -q install -r gateway/manager-api/requirements.txt websockets httpx cryptography python-multipart

echo "-- configuration (CONSTANT defaults — change them right after install) --"
if [ ! -f /etc/honorpro-gateway.env ]; then
cat > /etc/honorpro-gateway.env <<'ENV'
# HonorPro gateway — defaults are documented in the Broker Setup Guide.
# CHANGE ADMIN_PASSWORD AND HUB_OUTBOX_TOKEN IMMEDIATELY AFTER INSTALL.
BACKEND=mock
ADMIN_USER=admin
ADMIN_PASSWORD=HonorPro2026!
HUB_OUTBOX_TOKEN=hp-outbox-2026
HUB_LICENSE_PATH=/opt/honorpro/gateway/manager-api/hub_license.json
ENV
chmod 600 /etc/honorpro-gateway.env
fi

cat > /etc/systemd/system/honorpro-gateway.service <<'UNIT'
[Unit]
Description=HonorPro gateway (broker-side API)
After=network.target
[Service]
WorkingDirectory=/opt/honorpro/gateway/manager-api
EnvironmentFile=/etc/honorpro-gateway.env
ExecStart=/opt/honorpro/venv/bin/uvicorn app.server:app --host 127.0.0.1 --port 8120
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
UNIT

echo "-- enrolling the agent --"
cd /opt/honorpro/agent
AGENT_CONFIG=/opt/honorpro/agent/agent.json /opt/honorpro/venv/bin/python hub_agent.py --enroll "$ENROLL" --hub "$HUB"
/opt/honorpro/venv/bin/python - <<'PY'
import json
p = "/opt/honorpro/agent/agent.json"
cfg = json.load(open(p))
cfg["license_path"] = "/opt/honorpro/gateway/manager-api/hub_license.json"
cfg["gateway_url"] = "http://127.0.0.1:8120"
cfg["staging_dir"] = "/opt/honorpro/agent/staging"
cfg["outbox_token"] = "hp-outbox-2026"
cfg["config_paths"] = {"price-alerts": "/opt/honorpro/gateway/manager-api/price_alerts.json"}
json.dump(cfg, open(p, "w"), indent=2)
PY

cat > /etc/systemd/system/honorpro-agent.service <<'UNIT'
[Unit]
Description=HonorPro Hub Agent
After=network.target
[Service]
WorkingDirectory=/opt/honorpro/agent
Environment=AGENT_CONFIG=/opt/honorpro/agent/agent.json
ExecStart=/opt/honorpro/venv/bin/python /opt/honorpro/agent/hub_agent.py
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable --now honorpro-gateway honorpro-agent
sleep 4

echo
echo "================================================================"
echo " HonorPro broker side is up."
echo "   gateway:        http://127.0.0.1:8120  ($(systemctl is-active honorpro-gateway))"
echo "   admin console:  http://127.0.0.1:8120/api/admin"
echo "   agent:          $(systemctl is-active honorpro-agent) (enrolled with your hub)"
echo
echo " DEFAULT CREDENTIALS (constant — documented in the Broker Setup Guide):"
echo "   admin console:  admin / HonorPro2026!"
echo "   agent token:    hp-outbox-2026"
echo " >>> CHANGE BOTH NOW: edit /etc/honorpro-gateway.env, then"
echo " >>>   systemctl restart honorpro-gateway honorpro-agent"
echo
echo " Next steps (Broker Setup Guide, section 4):"
echo "   1. Install your entitled MT5 plugins (download them in your hub cabinet)."
echo "   2. Switch BACKEND=mock -> serverapi + BRIDGE_URL in /etc/honorpro-gateway.env."
echo "   3. Put the gateway behind your TLS proxy and open it to your terminal domain."
echo "================================================================"
