package system

import (
	"log"
	"time"

	"zlh-agent/internal/state"
)

/*
   autostart.go
   Handles:
     - Optional auto-start on LXC boot
     - Optional crash backoff / retry
     - Global control for enabling/disabling auto-start

   NOTE:
     - This file does NOT call StartServer automatically unless
       AutoStartEnabled == true.

     - The template can choose to enable auto-start by writing a small
       JSON flag into the payload config, or the API can set it.
*/

var AutoStartEnabled = false  // controlled by config or template
var AutoRestartOnCrash = true // can be disabled for debugging

/* --------------------------------------------------------------------------
   InitAutoStart — called from main.go
----------------------------------------------------------------------------*/

func InitAutoStart() {
	if !AutoStartEnabled {
		log.Println("[autostart] disabled (ok)")
		return
	}

	log.Println("[autostart] enabled: waiting for config...")

	go func() {
		// Wait until config is loaded
		for {
			cfg, err := state.LoadConfig()
			if err == nil && cfg != nil {
				log.Println("[autostart] config detected: boot-starting server")
				_ = StartServerReady(cfg)
				return
			}
			time.Sleep(3 * time.Second)
		}
	}()
}
