package main

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

func install() error {
	kioskInfof("checking firefox installation")
	var firefoxInstallErr error

	firefoxInstalled := isFirefoxInstalled()
	firefoxUsable := false
	if firefoxInstalled {
		firefoxUsable = isFirefoxUsable()
	}
	markerExists := hasFirefoxInstallMarker()
	kioskInfof("firefox startup state installed=%v usable=%v markerExists=%v", firefoxInstalled, firefoxUsable, markerExists)

	switch {
	case firefoxInstalled && firefoxUsable:
		kioskInfof("firefox installed and usable")
		fmt.Println("Firefox is installed and usable")
		if err := writeFirefoxInstallMarker("usable"); err != nil {
			kioskWarnf("write firefox install marker failed err=%v", err)
		}
	case firefoxInstalled:
		kioskWarnf("firefox is installed but version check failed; skip automatic reinstall")
		fmt.Println("Firefox installed but unusable; skip automatic reinstall on startup")
	case markerExists:
		kioskWarnf("firefox executable missing but install marker exists; skip automatic reinstall")
		fmt.Println("Firefox missing; skip automatic reinstall on startup")
	case shouldAutoInstallFirefox(firefoxInstalled, markerExists):
		kioskWarnf("firefox executable missing and no install marker; starting first-time install")
		fmt.Println("Firefox missing, installing...")
		if err := installFirefox(); err != nil {
			kioskErrorf("firefox first-time install failed err=%v", err)
			fmt.Printf("install Firefox failed: %v\n", err)
			firefoxInstallErr = fmt.Errorf("install Firefox failed: %w", err)
		} else {
			if err := writeFirefoxInstallMarker("installed"); err != nil {
				kioskWarnf("write firefox install marker after install failed err=%v", err)
			}
			kioskInfof("firefox first-time install success")
			fmt.Println("Firefox install success")
		}
	}

	appPath, err := os.Executable()
	if err != nil {
		kioskErrorf("read executable path failed err=%v", err)
		fmt.Printf("read executable path failed: %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("setting autostart...")
		if err := enableAutoStart(appPath); err != nil {
			kioskErrorf("autostart setup failed service=%s err=%v", autoStartServiceFile(appPath), err)
			fmt.Printf("setup autostart failed: %v\n", err)
			return fmt.Errorf("setup autostart failed: %w", err)
		}
		fmt.Println("autostart setup success")
	} else {
		fmt.Println("autostart already configured")
	}
	if firefoxInstallErr != nil {
		return firefoxInstallErr
	}
	return nil
}

func shouldAutoInstallFirefox(installed bool, markerExists bool) bool {
	return !installed && !markerExists
}
