#!/bin/sh
set -eu

export HWLAB_SERVICE_ID="hwlab-cloud-web"
export HWLAB_ARTIFACT_KIND="cloud-web"
export HWLAB_SERVICE_ENTRYPOINT="web/hwlab-cloud-web/index.html"
export HWLAB_RUNTIME_MODE="${HWLAB_RUNTIME_MODE:-env-reuse-git-mirror-checkout}"
export HWLAB_COMMIT_ID="${HWLAB_BOOT_COMMIT:?HWLAB_BOOT_COMMIT is required}"
export HWLAB_REVISION="${HWLAB_BOOT_COMMIT}"
export HWLAB_IMAGE="${HWLAB_ENVIRONMENT_IMAGE:-${HWLAB_IMAGE:-}}"
export HWLAB_IMAGE_DIGEST="${HWLAB_ENVIRONMENT_DIGEST:-${HWLAB_IMAGE_DIGEST:-unknown}}"
export PORT="${PORT:-${HWLAB_PORT:-8080}}"
export HWLAB_PORT="$PORT"

bun_bin="${HWLAB_BUN_COMMAND:-}"
if [ -z "$bun_bin" ]; then
  if command -v bun >/dev/null 2>&1; then
    bun_bin="$(command -v bun)"
  elif [ -x /usr/local/bin/bun ]; then
    bun_bin="/usr/local/bin/bun"
  elif [ -x ./node_modules/.bin/bun ]; then
    bun_bin="./node_modules/.bin/bun"
  else
    echo "hwlab-cloud-web boot failed: bun not found" >&2
    exit 127
  fi
fi

"$bun_bin" run --cwd web/hwlab-cloud-web build

cat > .hwlab-cloud-web-runtime.mjs <<'NODE'
import { Buffer } from "node:buffer";
import { serveCloudWeb } from "./internal/dev-entrypoint/cloud-web-runtime.mjs";

const port = Number.parseInt(process.env.PORT || process.env.HWLAB_PORT || "8080", 10);
const serviceId = process.env.HWLAB_SERVICE_ID || "hwlab-cloud-web";
const environment = process.env.HWLAB_ENVIRONMENT || "v02";
const processStartedAt = new Date();
const roots = [
  `${process.cwd()}/web/hwlab-cloud-web/dist`,
  `${process.cwd()}/web/hwlab-cloud-web`
];

function sendJson(response, statusCode, body) {
  const payload = JSON.stringify(body, null, 2);
  response.writeHead(statusCode, {
    "content-type": "application/json; charset=utf-8",
    "content-length": Buffer.byteLength(payload)
  });
  response.end(payload);
}

function imageTagFromReference(imageReference) {
  const source = String(imageReference || "").trim();
  const slashIndex = source.lastIndexOf("/");
  const colonIndex = source.lastIndexOf(":");
  if (colonIndex <= slashIndex) return null;
  return source.slice(colonIndex + 1) || null;
}

function shortRevision(value) {
  const source = String(value || "").trim();
  return source.length >= 12 ? source.slice(0, 12) : source || "unknown";
}

function healthPayload() {
  const commitId = process.env.HWLAB_COMMIT_ID || process.env.HWLAB_BOOT_COMMIT || "unknown";
  const imageReference = process.env.HWLAB_IMAGE || process.env.HWLAB_ENVIRONMENT_IMAGE || "unknown";
  return {
    serviceId,
    environment,
    status: "ok",
    artifactKind: "cloud-web",
    runtimeMode: process.env.HWLAB_RUNTIME_MODE || "env-reuse-git-mirror-checkout",
    revision: process.env.HWLAB_REVISION || commitId,
    commit: {
      id: commitId,
      source: process.env.HWLAB_BUILD_SOURCE || "git-mirror-runtime-checkout"
    },
    image: {
      reference: imageReference,
      tag: imageTagFromReference(imageReference) || shortRevision(commitId),
      digest: process.env.HWLAB_IMAGE_DIGEST || process.env.HWLAB_ENVIRONMENT_DIGEST || "unknown"
    },
    boot: {
      repo: process.env.HWLAB_BOOT_REPO || null,
      commit: process.env.HWLAB_BOOT_COMMIT || null,
      script: process.env.HWLAB_BOOT_SH || null
    },
    build: {
      source: process.env.HWLAB_BUILD_SOURCE || "runtime-boot:web-build",
      metadataSource: "runtime-boot"
    },
    process: {
      pid: process.pid,
      startedAt: processStartedAt.toISOString(),
      uptimeSeconds: Math.round((Date.now() - processStartedAt.getTime()) / 1000)
    }
  };
}

await serveCloudWeb({ port, serviceId, healthPayload, sendJson, roots });
NODE

exec "$bun_bin" .hwlab-cloud-web-runtime.mjs
