package codeserver

import (
	"fmt"
	"strconv"

	"zlh-agent/internal/provision/executil"
	"zlh-agent/internal/state"
)

func launchEnv(cfg state.Config) []string {
	extraEnv := []string{
		"CODE_SERVER_PORT=6000",
		"CODE_SERVER_WORKSPACE=/home/dev/workspace",
	}
	if cfg.VMID != 0 {
		extraEnv = append(
			extraEnv,
			"VMID="+strconv.Itoa(cfg.VMID),
		)
	}
	return extraEnv
}

func Install(cfg state.Config) error {
	if Running() {
		if err := Stop(); err != nil {
			return fmt.Errorf("codeserver stop failed before install: %w", err)
		}
	}
	if err := executil.RunEmbeddedScript("addons/codeserver/install.sh", launchEnv(cfg)...); err != nil {
		return fmt.Errorf("codeserver install failed: %w", err)
	}
	return nil
}
