/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { readFile, unlink } from "node:fs/promises";
class RestartFlagMonitor {
  #hostPath;
  #subject;
  #active = false;
  #polling;
  constructor(hostPath, subject) {
    this.#hostPath = hostPath;
    this.#subject = subject;
  }
  start() {
    if (this.#active) {
      return;
    }
    this.#active = true;
    this.#polling = this.#poll();
  }
  async stop() {
    this.#active = false;
    await this.#polling;
    this.#polling = void 0;
  }
  async #poll() {
    while (this.#active) {
      let content;
      try {
        content = (await readFile(this.#hostPath, "utf-8")).trim();
      } catch (e) {
        if (e.code !== "ENOENT") {
          console.warn("Error reading restart flag file:", e);
        }
      }
      if (content) {
        await this.#handle(content);
        try {
          await unlink(this.#hostPath);
        } catch (e) {
          if (e.code !== "ENOENT") {
            console.warn("Failed to delete restart flag file:", e);
          }
        }
      }
      await new Promise((resolve) => setTimeout(resolve, 100));
    }
  }
  async #handle(content) {
    switch (content) {
      case "restart":
        await this.#subject.backchannel({ name: "reboot" });
        break;
      case "factory reset":
      case "factory reset app only":
        await this.#subject.backchannel({ name: "factoryReset" });
        break;
      default:
        throw new Error(`Unknown restart flag content: "${content}"`);
    }
  }
}
export {
  RestartFlagMonitor
};
//# sourceMappingURL=restart-flag-monitor.js.map
