#!/bin/sh
set -euxo pipefail

service_name="bmc-nix-service-orchestrator"
instance_name="main"
executable="/nix/store/931y750phcbxq7djvj5y08q10w9vkr56-bmc-nix-service-orchestrator-wrapped/bin/bmc-nix-service-orchestrator"
current_link="$(dirname "$PROFILE_NEW_GENERATION")/current"

# Remove a stale instance from a previous activation, if any.
ubus call service delete "{\"name\":\"$service_name\"}" 2>/dev/null || true

# Register a one-shot procd instance for the orchestrator.
ubus call service set "{
  \"name\": \"$service_name\",
  \"instances\": {
    \"$instance_name\": {
      \"command\": [
        \"$executable\",
        \"--old-generation=$PROFILE_OLD_GENERATION\",
        \"--new-generation=$PROFILE_NEW_GENERATION\",
        \"--current-link=$current_link\",
        \"--instance-name=$service_name\",
        \"--timeout-seconds=300\"
      ],
      \"stdout\": true,
      \"stderr\": true
    }
  }
}"
