#!/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)
#
# Update Odoo modules: stop service, upgrade module(s), restart service.
#
# Usage: bin/update [module ...]
#   bin/update             Upgrade the 'base' module (full update)
#   bin/update sale        Upgrade the 'sale' module
#   bin/update sale stock  Upgrade 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="${*:-base}"
info "Updating 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

# Upgrade modules.
info "Upgrading module(s): ${modules}..."
"${PYTHON}" "${ODOO_BIN}" --config "${CONFIG}" -d "$DB" -u "$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 "Update complete. Start with: bin/run"
fi
