#!/usr/bin/env bash
# Copyright 2026 - Ronald Portier (Open Eye Development)
# SPDX-License-Identifier: AGPL-3.0-or-later  (https://www.gnu.org/licenses/agpl.html)
#
# Install Odoo modules: stop service, install module(s), restart service.
#
# Usage: bin/install <module ...>
#   bin/install sale        Install the 'sale' module
#   bin/install sale stock  Install both 'sale' and 'stock'
#
# In production: stops/starts the systemd service (requires sudo).
# In dev: no service to stop; prints a reminder to start with bin/run.

set -euo pipefail

BUILD_DIR="$(cd "$(dirname "$0")/.." && pwd)"
INSTANCE="$(basename "$(dirname "$BUILD_DIR")")"
SERVICE="odoo-${INSTANCE}"
PYTHON="${BUILD_DIR}/.venv/bin/python"
ODOO_BIN="${BUILD_DIR}/parts/odoo/odoo-bin"
CONFIG="${BUILD_DIR}/etc/odoo.conf"
DB="${INSTANCE}"

info()  { echo "[INFO]  $*"; }
error() { echo "[ERROR] $*" >&2; exit 1; }

# Dev instances have no systemd service file.
SVC_FILE="/etc/systemd/system/${SERVICE}.service"
[[ -f "$SVC_FILE" ]] && IS_DEV=0 || IS_DEV=1

modules="${*:-}"
[[ -n "$modules" ]] || { echo "Usage: bin/install <module ...>" >&2; exit 1; }

info "Installing module(s): ${modules}"

if [[ "$IS_DEV" -eq 0 ]]; then
    # Production: stop the service (no-op if already stopped).
    info "Stopping ${SERVICE}..."
    sudo systemctl stop "$SERVICE" 2>/dev/null || true
fi

# Install modules.
info "Installing module(s): ${modules}..."
"${PYTHON}" "${ODOO_BIN}" --config "${CONFIG}" -d "$DB" -i "$modules" --stop-after-init

if [[ "$IS_DEV" -eq 0 ]]; then
    # Production: restart the service.
    info "Starting ${SERVICE}..."
    sudo systemctl start "$SERVICE"
    sleep 3
    if systemctl is-active --quiet "$SERVICE"; then
        info "${SERVICE} is running."
    else
        error "${SERVICE} failed to start. Check: journalctl -u ${SERVICE} -n 50"
    fi
else
    info "Install complete. Start with: bin/run"
fi
