#!/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)
#
# Start the Odoo instance.
#
# Usage: bin/start
#
# In production: starts the systemd service (requires sudo).
# In dev: launches Odoo in the foreground via bin/run (Ctrl-C to stop).

set -euo pipefail

BUILD_DIR="$(cd "$(dirname "$0")/.." && pwd)"
INSTANCE="$(basename "$(dirname "$BUILD_DIR")")"
SERVICE="odoo-${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

if [[ "$IS_DEV" -eq 1 ]]; then
    info "Dev instance — starting in foreground (Ctrl-C to stop)..."
    exec "$(dirname "$0")/run"
fi

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
