Skip to content

start_ems.sh

#!/usr/bin/env bash
# start_ems.sh
# Start the complete EMS stack using the same supervisor used by Docker.
set -Eeuo pipefail

GREEN="\033[1;32m"
RED="\033[1;31m"
YELLOW="\033[1;33m"
NC="\033[0m"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

SUPERVISOR="${EMS_START_SCRIPT:-$SCRIPT_DIR/start_ems_client_in_docker.sh}"
LOG_DIR="${LOG_DIR:-/app/logs}"
START_LOG="${START_LOG:-$LOG_DIR/start_ems_client.log}"

# ------------------------------------------------------------------
# EMS API token
# Source: emsConfig/ems/ems_api_config.json
# The JSON may contain either:
#   "bearer_token": "Bearer <token>"
# or:
#   "bearer_token": "<token>"
#
# ems_settings_api.py adds "Bearer " itself, so normalize to raw token.
# ------------------------------------------------------------------
EMS_API_CONFIG_FILE="${EMS_API_CONFIG_FILE:-$SCRIPT_DIR/emsConfig/ems/ems_api_config.json}"

load_ems_api_token() {
    if [[ ! -f "$EMS_API_CONFIG_FILE" ]]; then
        echo -e "${RED:-}[ERROR] EMS API config not found: $EMS_API_CONFIG_FILE${NC:-}" >&2
        return 1
    fi

    local token
    token="$(
        python3 - "$EMS_API_CONFIG_FILE" <<'PY'
import json
import sys

path = sys.argv[1]

try:
    with open(path, "r", encoding="utf-8") as f:
        cfg = json.load(f)
except Exception as exc:
    print(f"ERROR: unable to read JSON: {exc}", file=sys.stderr)
    raise SystemExit(2)

token = str(
    cfg.get("ems_control_json", {}).get("bearer_token", "")
).strip()

if token.lower().startswith("bearer "):
    token = token[7:].strip()

if not token:
    print(
        "ERROR: ems_control_json.bearer_token is missing or empty",
        file=sys.stderr,
    )
    raise SystemExit(3)

print(token)
PY
    )" || return 1

    export EMS_SETTINGS_API_TOKEN="$token"
    export EMS_HARDWARE_BEARER_TOKEN="$token"

    echo -e "${GREEN:-}[OK] EMS API token loaded from $EMS_API_CONFIG_FILE${NC:-}"
}


print_help() {
    cat <<'EOF'
Usage:
  ./start_ems.sh [OPTION]

Options:
  --foreground    Run start_ems_client_in_docker.sh in foreground
  --restart       Stop existing EMS processes first, then start
  --status        Show EMS process status
  -h, --help      Show this help

Default:
  Starts start_ems_client_in_docker.sh in background with nohup.

Environment variables:
  EMS_START_SCRIPT   Override supervisor script path
  LOG_DIR            EMS log directory (default: /app/logs)
  START_LOG          Supervisor log file

Examples:
  ./start_ems.sh
  ./start_ems.sh --restart
  ./start_ems.sh --foreground
  ./start_ems.sh --status
EOF
}

status() {
    echo -e "${YELLOW}[INFO] EMS process status:${NC}"
    local found=0

    for pattern in \
        "start_ems_client_in_docker.sh" \
        "ems_settings_api.py" \
        "file_sync.py" \
        "folder_sync.py" \
        "folder_cleaner.py" \
        "pcs_client_save_data_v20_ES100CX12S.py" \
        "gridMeter_client_save_data_v13.py" \
        "solarMeter_client_save_data_v13.py" \
        "ems_main.py"
    do
        if pgrep -af "$pattern" 2>/dev/null | grep -v "grep" | grep -v "start_ems.sh --status"; then
            found=1
        fi
    done

    if [[ "$found" -eq 0 ]]; then
        echo -e "${YELLOW}[INFO] No EMS processes found.${NC}"
        return 1
    fi
}

is_running() {
    pgrep -f '[s]tart_ems_client_in_docker\.sh' >/dev/null 2>&1
}

MODE="background"

case "${1:-}" in
    "")
        ;;
    --foreground)
        MODE="foreground"
        ;;
    --restart)
        MODE="restart"
        ;;
    --status)
        status || true
        exit 0
        ;;
    -h|--help)
        print_help
        exit 0
        ;;
    *)
        echo -e "${RED}[ERROR] Unknown option: $1${NC}"
        print_help
        exit 1
        ;;
esac

load_ems_api_token

if [[ ! -f "$SUPERVISOR" ]]; then
    echo -e "${RED}[ERROR] EMS supervisor not found:${NC}"
    echo "        $SUPERVISOR"
    exit 1
fi

if [[ ! -r "$SUPERVISOR" ]]; then
    echo -e "${RED}[ERROR] EMS supervisor is not readable: $SUPERVISOR${NC}"
    exit 1
fi

if [[ "$MODE" == "restart" ]]; then
    if [[ -x "$SCRIPT_DIR/stop_ems.sh" ]]; then
        echo -e "${YELLOW}[INFO] Stopping existing EMS processes first...${NC}"
        "$SCRIPT_DIR/stop_ems.sh" --clients || true
    else
        echo -e "${YELLOW}[WARN] stop_ems.sh not found/executable; continuing.${NC}"
    fi
elif is_running; then
    echo -e "${YELLOW}[WARN] EMS supervisor is already running.${NC}"
    status || true
    echo
    echo "Use:"
    echo "  ./start_ems.sh --restart"
    exit 0
fi

mkdir -p "$LOG_DIR"

echo -e "${YELLOW}[INFO] Starting complete EMS stack using:${NC}"
echo "       $SUPERVISOR"

if [[ "$MODE" == "foreground" ]]; then
    echo -e "${YELLOW}[INFO] Running EMS in foreground...${NC}"
    exec bash "$SUPERVISOR"
fi

: > "$START_LOG"

nohup bash "$SUPERVISOR" >>"$START_LOG" 2>&1 &
PID=$!

sleep 2

if kill -0 "$PID" >/dev/null 2>&1; then
    echo -e "${GREEN}[OK] EMS supervisor started successfully.${NC}"
    echo -e "${GREEN}[OK] PID: $PID${NC}"
    echo -e "${GREEN}[OK] Supervisor log: $START_LOG${NC}"
    echo
    status || true
else
    echo -e "${RED}[ERROR] EMS supervisor failed to start.${NC}"
    echo -e "${YELLOW}[INFO] Last log lines:${NC}"
    tail -n 120 "$START_LOG" 2>/dev/null || true
    exit 1
fi