Gitfed
bastien-mrq/sssh / internal / store / store.go
// Package store gère la persistance des hosts et profils VPN dans hosts.toml.
package store

import (
	"fmt"
	"os"
	"path/filepath"
	"sort"
	"strings"

	"github.com/pelletier/go-toml/v2"

	"git.neuromancer.ovh/bastien-mrq/sssh/internal/host"
	"git.neuromancer.ovh/bastien-mrq/sssh/internal/vpn"
)

// File est le format de hosts.toml (aussi celui d'export/import).
type File struct {
	Hosts map[string]host.Host   `toml:"hosts"`
	VPN   map[string]vpn.Profile `toml:"vpn,omitempty"`
}

// Store est le contenu chargé de hosts.toml.
type Store struct {
	path  string
	Hosts map[string]host.Host
	VPNs  map[string]vpn.Profile
}

// Path rend le chemin du fichier de configuration : $SSSH_CONFIG, sinon
// ~/.config/sssh/hosts.toml (ou $XDG_CONFIG_HOME). L'emplacement historique
// (os.UserConfigDir, ~/Library/Application Support sur macOS) reste utilisé
// s'il existe et que le nouveau n'existe pas.
func Path() string {
	if p := os.Getenv("SSSH_CONFIG"); p != "" {
		return p
	}
	xdg := os.Getenv("XDG_CONFIG_HOME")
	if xdg == "" {
		home, err := os.UserHomeDir()
		if err != nil {
			home = os.Getenv("HOME")
		}
		xdg = filepath.Join(home, ".config")
	}
	p := filepath.Join(xdg, "sssh", "hosts.toml")
	if _, err := os.Stat(p); err == nil {
		return p
	}
	if base, err := os.UserConfigDir(); err == nil {
		legacy := filepath.Join(base, "sssh", "hosts.toml")
		if _, err := os.Stat(legacy); err == nil {
			return legacy
		}
	}
	return p
}

// Load lit hosts.toml ; un fichier absent donne un store vide.
func Load() (*Store, error) {
	s := &Store{path: Path(), Hosts: map[string]host.Host{}, VPNs: map[string]vpn.Profile{}}
	data, err := os.ReadFile(s.path)
	if os.IsNotExist(err) {
		return s, nil
	}
	if err != nil {
		return nil, err
	}
	var f File
	if err := toml.Unmarshal(data, &f); err != nil {
		return nil, fmt.Errorf("%s : %w", s.path, err)
	}
	if f.Hosts != nil {
		s.Hosts = f.Hosts
	}
	if f.VPN != nil {
		s.VPNs = f.VPN
	}
	return s, nil
}

// Save écrit le fichier de façon atomique (fichier temporaire puis rename).
func (s *Store) Save() error {
	data, err := s.Marshal()
	if err != nil {
		return err
	}
	if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil {
		return err
	}
	tmp := s.path + ".tmp"
	if err := os.WriteFile(tmp, data, 0o600); err != nil {
		return err
	}
	return os.Rename(tmp, s.path)
}

// Marshal sérialise le store au format hosts.toml.
func (s *Store) Marshal() ([]byte, error) {
	f := File{Hosts: s.Hosts}
	if len(s.VPNs) > 0 {
		f.VPN = s.VPNs
	}
	return toml.Marshal(f)
}

// Get rend le host nommé, avec son Name renseigné.
func (s *Store) Get(name string) (host.Host, bool) {
	h, ok := s.Hosts[name]
	if ok {
		h.Name = name
	}
	return h, ok
}

// Set ajoute ou remplace un host.
func (s *Store) Set(h host.Host) {
	s.Hosts[h.Name] = h
}

// Remove supprime un host ; rend false s'il n'existait pas.
func (s *Store) Remove(name string) bool {
	if _, ok := s.Hosts[name]; !ok {
		return false
	}
	delete(s.Hosts, name)
	return true
}

// List rend les hosts triés par nom.
func (s *Store) List() []host.Host {
	hosts := make([]host.Host, 0, len(s.Hosts))
	for name, h := range s.Hosts {
		h.Name = name
		hosts = append(hosts, h)
	}
	sort.Slice(hosts, func(i, j int) bool { return hosts[i].Name < hosts[j].Name })
	return hosts
}

// VPN rend le profil VPN nommé.
func (s *Store) VPN(name string) (vpn.Profile, bool) {
	p, ok := s.VPNs[name]
	return p, ok
}

// SetVPN ajoute ou remplace un profil VPN.
func (s *Store) SetVPN(name string, p vpn.Profile) {
	s.VPNs[name] = p
}

// RemoveVPN supprime un profil VPN ; rend false s'il n'existait pas.
func (s *Store) RemoveVPN(name string) bool {
	if _, ok := s.VPNs[name]; !ok {
		return false
	}
	delete(s.VPNs, name)
	return true
}

// VPNNames rend les noms de profils VPN triés.
func (s *Store) VPNNames() []string {
	names := make([]string, 0, len(s.VPNs))
	for n := range s.VPNs {
		names = append(names, n)
	}
	sort.Strings(names)
	return names
}

// HostsUsingVPN rend les noms des hosts qui référencent ce profil.
func (s *Store) HostsUsingVPN(name string) []string {
	var out []string
	for _, h := range s.List() {
		if h.VPN == name {
			out = append(out, h.Name)
		}
	}
	return out
}

// Resolve cherche name parmi hosts : correspondance exacte d'abord,
// sinon préfixe unique. En cas d'ambiguïté, l'erreur liste les candidats.
func Resolve(hosts []host.Host, name string) (host.Host, error) {
	var candidates []host.Host
	for _, h := range hosts {
		if h.Name == name {
			return h, nil
		}
		if strings.HasPrefix(h.Name, name) {
			candidates = append(candidates, h)
		}
	}
	switch len(candidates) {
	case 1:
		return candidates[0], nil
	case 0:
		return host.Host{}, fmt.Errorf("host inconnu : %q (voir sssh list)", name)
	default:
		names := make([]string, len(candidates))
		for i, h := range candidates {
			names[i] = h.Name
		}
		return host.Host{}, fmt.Errorf("%q est ambigu : %s", name, strings.Join(names, ", "))
	}
}