package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func install() error {
	kioskInfof("checking firefox usability")
	// 1. 检查并修复 Firefox
	if !isFirefoxUsable() {
		kioskWarnf("firefox unusable; starting install/repair")
		fmt.Println("Firefox missing or unusable, installing/repairing...")
		if err := installFirefox(); err != nil {
			kioskErrorf("firefox install/repair failed err=%v", err)
			fmt.Printf("install/repair Firefox failed: %v\n", err)
			return fmt.Errorf("install/repair Firefox failed: %w", err)
		}
		kioskInfof("firefox install/repair success")
		fmt.Println("Firefox install/repair success")
	} else {
		kioskInfof("firefox is usable")
		fmt.Println("Firefox is installed and usable")
	}

	// 2. 设置当前应用开机自启动
	appPath, err := os.Executable()
	if err != nil {
		kioskErrorf("read executable path failed err=%v", err)
		fmt.Printf("读取应用路径失败: %v\n", err)
		return fmt.Errorf("read executable path failed: %w", err)
	}

	kioskInfof("current executable path=%s workdir=%s", appPath, filepath.Dir(appPath))
	if !isAutoStartEnabled(appPath) {
		kioskWarnf("autostart service missing or mismatched; reinstalling service=%s", autoStartServiceFile(appPath))
		fmt.Println("正在设置开机自启动...")
		if err := enableAutoStart(appPath); err != nil {
			kioskErrorf("autostart setup failed service=%s err=%v", autoStartServiceFile(appPath), err)
			fmt.Printf("设置开机自启动失败: %v\n", err)
			return fmt.Errorf("setup autostart failed: %w", err)
		}
		fmt.Println("开机自启动设置成功")
	} else {
		fmt.Println("已设置开机自启动")
	}
	return nil
}
