//go:build linux

package startup

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

const DesktopFileName = "mirage-qt.desktop"

type Controller struct {
	ConfigHome string
	ExecPath   func() (string, error)
}

func (c Controller) autostartDir() (string, error) {
	if c.ConfigHome != "" {
		return filepath.Join(c.ConfigHome, "autostart"), nil
	}
	if xdg := os.Getenv("XDG_CONFIG_HOME"); xdg != "" {
		return filepath.Join(xdg, "autostart"), nil
	}
	home, err := os.UserHomeDir()
	if err != nil {
		if u, uerr := user.Current(); uerr == nil {
			home = u.HomeDir
		} else {
			return "", err
		}
	}
	return filepath.Join(home, ".config", "autostart"), nil
}

func (c Controller) desktopPath() (string, error) {
	dir, err := c.autostartDir()
	if err != nil {
		return "", err
	}
	return filepath.Join(dir, DesktopFileName), nil
}

func (c Controller) Enabled() (bool, error) {
	path, err := c.desktopPath()
	if err != nil {
		return false, err
	}
	_, err = os.Stat(path)
	switch {
	case err == nil:
		return true, nil
	case os.IsNotExist(err):
		return false, nil
	default:
		return false, err
	}
}

func (c Controller) SetEnabled(enabled bool) error {
	path, err := c.desktopPath()
	if err != nil {
		return err
	}
	if !enabled {
		if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
			return err
		}
		return nil
	}
	if c.ExecPath == nil {
		return errors.New("exec path callback is nil")
	}
	exe, err := c.ExecPath()
	if err != nil {
		return err
	}
	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
		return err
	}
	content := fmt.Sprintf(`[Desktop Entry]
Type=Application
Version=1.0
Name=Mirage
Comment=Mirage Linux tray client
Exec=%s
Terminal=false
Categories=Network;
X-GNOME-Autostart-enabled=true
`, exe)
	return os.WriteFile(path, []byte(content), 0o644)
}
