package main

import (
	"fmt"
	"os"
	"os/exec"
	"strings"

	"github.com/towgo/towgo/lib/system"
	g "tgk-touch/internal/global"
)

func isFirefoxUsable() bool {
	cmd := exec.Command("firefox", "--version")
	out, err := cmd.CombinedOutput()
	ok := err == nil
	kioskInfof("firefox usability check ok=%v output=%q err=%v", ok, strings.TrimSpace(string(out)), err)
	return ok
}

func isFirefoxInstalled() bool {
	cmd := exec.Command("which", "firefox")
	out, err := cmd.CombinedOutput()
	ok := err == nil
	kioskDebugf("firefox install path check ok=%v output=%q err=%v", ok, strings.TrimSpace(string(out)), err)
	return ok
}

func installFirefox() error {
	var p struct {
		DebPkgPath       string `json:"DebPkgPath"`
		DebPkgName       string `json:"DebPkgName"`
		InstallShellPath string `json:"InstallShellPath"`
	}
	p.DebPkgPath = g.Config().Firefox.DebPkgPath
	p.DebPkgName = g.Config().Firefox.DebPkgName
	p.InstallShellPath = g.Config().Firefox.InstallShellPath
	kioskInfof("firefox install begin programPath=%s debPath=%s debName=%s installShell=%s", system.GetPathOfProgram(), p.DebPkgPath, p.DebPkgName, p.InstallShellPath)

	command := exec.Command("sudo", "sh", "-c", fmt.Sprintf(`
echo "=== 当前工作目录 ==="
pwd
echo ""

echo "=== 卸载旧版 Firefox ==="
dpkg -P firefox || echo "警告：卸载旧版 Firefox 失败（可能未安装）"
echo ""

echo "=== 清理残留文件 ==="
rm -rf /opt/firefox* 2>/dev/null
echo ""

echo "=== 开始安装 Firefox ==="
echo "1. 复制安装包到 /opt 目录..."
cp -v %s%s/%s /opt/firefox-deb.tar.gz || { echo "错误：复制安装包失败"; exit 1; }
echo ""

echo "2. 解压安装包..."
cd /opt && tar -xzvf firefox-deb.tar.gz || { echo "错误：解压失败"; exit 1; }
echo ""

echo "3. 安装依赖和主程序..."
cd /opt/firefox-deb && sudo dpkg -i *.deb || { echo "错误：安装 deb 包失败"; exit 1; }
echo ""

echo "4. 验证安装..."
firefox --version || { echo "错误：Firefox 未正确安装"; exit 1; }
echo ""

echo "=== Firefox 安装完成 ==="
`, system.GetPathOfProgram(), p.DebPkgPath, p.DebPkgName))
	command.Stdout = os.Stdout
	command.Stderr = os.Stderr

	err := command.Run()
	if err != nil {
		kioskErrorf("firefox install command failed err=%v", err)
		return err
	}
	kioskInfof("firefox install command finished successfully")
	return nil
}
