// Package config leest het YAML-configuratiebestand van BlueGit.
package config

import (
	"fmt"
	"net"
	"net/url"
	"os"
	"strconv"
	"strings"

	"gitlab.com/Timfa/bluegit/internal/realip"
	"gopkg.in/yaml.v3"
)

// Config is de installatie op de mini-PC.
type Config struct {
	BaseURL string `yaml:"base_url"`
	Listen  string `yaml:"listen"`
	// StatePath is de kleine map met database, sleutel en het gekozen
	// opslagpad. Leeg wordt /var/lib/bluegit.
	StatePath string `yaml:"state_path"`
	// StoragePath is optioneel. Leeg betekent dat de beheerder het pad
	// in de webinterface kiest. Er is geen standaardpad.
	StoragePath    string   `yaml:"storage_path"`
	TrustedProxies []string `yaml:"trusted_proxies"`
	// BehindProxy is het oude veld. Het wordt geweigerd: één boolean
	// vertrouwt ofwel iedereen, ofwel niemand. De lijst hierboven beslist.
	BehindProxy bool   `yaml:"behind_proxy"`
	Auth        Auth   `yaml:"auth"`
	Git         Git    `yaml:"git"`
	SSH         SSH    `yaml:"ssh"`
	Runner      Runner `yaml:"runner"`
	CI          CI     `yaml:"ci"`

	proxies *realip.Set
}

// Auth wijst naar auth.timfalken.com of naar de lokale ontwikkelmodus.
type Auth struct {
	Mode             string `yaml:"mode"`
	BaseURL          string `yaml:"base_url"`
	ClientID         string `yaml:"client_id"`
	ClientSecret     string `yaml:"client_secret"`
	ClientSecretFile string `yaml:"client_secret_file"`
	RedirectPath     string `yaml:"redirect_path"`
	UserAgent        string `yaml:"user_agent"`
	DevUser          string `yaml:"dev_user"`
	DevAuthID        int64  `yaml:"dev_auth_id"`
}

// Git wijst naar de git-binary en de standaardbranch van nieuwe repositories.
type Git struct {
	Binary        string `yaml:"binary"`
	DefaultBranch string `yaml:"default_branch"`
	HookBinary    string `yaml:"hook_binary"`
}

// SSH is de git-over-SSH-listener en het adres dat in clone-URL's staat.
// Listen is waar dit proces bindt. PublicHost en PublicPort zijn wat
// een gebruiker ziet; de ingress kan daar een andere poort voor gebruiken.
type SSH struct {
	Enabled    bool   `yaml:"enabled"`
	Listen     string `yaml:"listen"`
	PublicHost string `yaml:"public_host"`
	PublicPort int    `yaml:"public_port"`
}

// Runner is de ingebouwde Docker-runner.
type Runner struct {
	Name string `yaml:"name"`
}

// CI stuurt de Docker-runner.
type CI struct {
	Enabled     bool   `yaml:"enabled"`
	Docker      string `yaml:"docker_binary"`
	Concurrency int    `yaml:"concurrency"`
	Network     string `yaml:"network"`
	TimeoutSec  int    `yaml:"timeout_seconds"`
}

// Load leest path en vult ontbrekende waarden aan.
func Load(path string) (Config, error) {
	raw, err := os.ReadFile(path)
	if err != nil {
		return Config{}, fmt.Errorf("config lezen: %w", err)
	}
	var c Config
	if err := yaml.Unmarshal(raw, &c); err != nil {
		return Config{}, fmt.Errorf("config: %w", err)
	}
	c.applyDefaults()
	if v := os.Getenv("BLUEGIT_STATE_PATH"); v != "" {
		c.StatePath = v
	}
	if v := os.Getenv("BLUEGIT_STORAGE_PATH"); v != "" {
		c.StoragePath = v
	}
	if v := os.Getenv("BLUEGIT_LISTEN"); v != "" {
		c.Listen = v
	}
	if v := os.Getenv("BLUEGIT_AUTH_CLIENT_SECRET"); v != "" {
		c.Auth.ClientSecret = v
	}
	if c.Auth.ClientSecret == "" && c.Auth.ClientSecretFile != "" {
		b, err := os.ReadFile(c.Auth.ClientSecretFile)
		if err != nil {
			return Config{}, fmt.Errorf("clientgeheim: %w", err)
		}
		c.Auth.ClientSecret = strings.TrimSpace(string(b))
	}
	if err := c.Validate(); err != nil {
		return Config{}, err
	}
	return c, nil
}

func (c *Config) applyDefaults() {
	if c.Listen == "" {
		c.Listen = "127.0.0.1:8080"
	}
	if c.StatePath == "" {
		c.StatePath = "/var/lib/bluegit"
	}
	if c.Auth.Mode == "" {
		c.Auth.Mode = "oauth"
	}
	if c.Auth.BaseURL == "" {
		c.Auth.BaseURL = "https://auth.timfalken.com"
	}
	if c.Auth.RedirectPath == "" {
		c.Auth.RedirectPath = "/auth/callback"
	}
	if c.Auth.UserAgent == "" {
		c.Auth.UserAgent = "BlueGitAccountClient/0.1"
	}
	if c.Auth.DevUser == "" {
		c.Auth.DevUser = "tim"
	}
	if c.Auth.DevAuthID == 0 {
		c.Auth.DevAuthID = 1
	}
	if c.Git.Binary == "" {
		c.Git.Binary = "git"
	}
	if c.Git.DefaultBranch == "" {
		c.Git.DefaultBranch = "master"
	}
	if c.SSH.Listen == "" {
		c.SSH.Listen = "0.0.0.0:2222"
	}
	if c.CI.Docker == "" {
		c.CI.Docker = "docker"
	}
	if c.CI.Concurrency <= 0 {
		c.CI.Concurrency = 1
	}
	if c.CI.Network == "" {
		c.CI.Network = "bridge"
	}
	if c.CI.TimeoutSec <= 0 {
		c.CI.TimeoutSec = 1800
	}
	if strings.TrimSpace(c.Runner.Name) == "" {
		c.Runner.Name = "Steve"
	} else {
		c.Runner.Name = strings.TrimSpace(c.Runner.Name)
	}
	c.Auth.BaseURL = strings.TrimRight(c.Auth.BaseURL, "/")
	c.BaseURL = strings.TrimRight(c.BaseURL, "/")
}

// Validate keurt een configuratie goed of af.
func (c *Config) Validate() error {
	if c.BaseURL == "" {
		return fmt.Errorf("base_url ontbreekt")
	}
	u, err := url.Parse(c.BaseURL)
	if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
		return fmt.Errorf("base_url moet een absolute http(s)-URL zijn")
	}
	if strings.TrimSpace(c.StatePath) == "" {
		return fmt.Errorf("state_path ontbreekt")
	}
	if !strings.HasPrefix(c.Auth.RedirectPath, "/") {
		return fmt.Errorf("auth.redirect_path moet met / beginnen")
	}
	switch c.Auth.Mode {
	case "oauth":
		if c.Auth.ClientID == "" || c.Auth.ClientSecret == "" {
			return fmt.Errorf("oauth vereist auth.client_id en een clientgeheim (veld, bestand of BLUEGIT_AUTH_CLIENT_SECRET)")
		}
		if c.Auth.BaseURL == "" {
			return fmt.Errorf("auth.base_url ontbreekt")
		}
	case "dev":
		if strings.EqualFold(u.Hostname(), "git.timfalken.com") {
			return fmt.Errorf("auth.mode dev is geweigerd voor git.timfalken.com")
		}
	default:
		return fmt.Errorf("auth.mode moet oauth of dev zijn")
	}
	if c.BehindProxy {
		return fmt.Errorf("behind_proxy doet niets meer; zet trusted_proxies op het IP of CIDR van de ingress en haal behind_proxy weg")
	}
	set, err := realip.Parse(c.TrustedProxies)
	if err != nil {
		return err
	}
	c.proxies = set
	if c.SSH.PublicPort < 0 || c.SSH.PublicPort > 65535 {
		return fmt.Errorf("ssh.public_port moet tussen 0 en 65535 liggen")
	}
	if h := strings.TrimSpace(c.SSH.PublicHost); h != "" {
		if strings.Contains(h, "://") || strings.ContainsAny(h, " /") || (strings.Contains(h, ":") && net.ParseIP(h) == nil) {
			return fmt.Errorf("ssh.public_host moet een hostnaam of IP zijn, zonder schema of poort")
		}
	}
	if _, _, err := net.SplitHostPort(c.SSH.Listen); err != nil {
		return fmt.Errorf("ssh.listen moet host:poort zijn")
	}
	return nil
}

// ProxySet is de geparsede trusted_proxies-lijst. Nil betekent dat
// niemand vertrouwd wordt.
func (c Config) ProxySet() *realip.Set { return c.proxies }

// SSHPublicHost is de host in een SSH-clone-URL.
// Leeg in de config: de host van base_url.
func (c Config) SSHPublicHost() string {
	if h := strings.TrimSpace(c.SSH.PublicHost); h != "" {
		return h
	}
	u, err := url.Parse(c.BaseURL)
	if err != nil {
		return ""
	}
	return u.Hostname()
}

// SSHPublicPort is de poort in een SSH-clone-URL.
// 0 in de config: de poort van ssh.listen.
func (c Config) SSHPublicPort() int {
	if c.SSH.PublicPort > 0 {
		return c.SSH.PublicPort
	}
	_, port, err := net.SplitHostPort(c.SSH.Listen)
	if err != nil {
		return 22
	}
	n, err := strconv.Atoi(port)
	if err != nil || n <= 0 {
		return 22
	}
	return n
}

// CloneSSH is de URL die een gebruiker kloont. Leeg als SSH uit staat.
func (c Config) CloneSSH(repoPath string) string {
	if !c.SSH.Enabled {
		return ""
	}
	host := c.SSHPublicHost()
	if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") {
		host = "[" + host + "]"
	}
	return fmt.Sprintf("ssh://git@%s:%d/%s.git", host, c.SSHPublicPort(), repoPath)
}

// RedirectURI is de callback die bij de auth-server geregistreerd moet staan.
func (c Config) RedirectURI() string {
	return c.BaseURL + c.Auth.RedirectPath
}

// Example is een startconfiguratie voor de mini-PC.
func Example() string {
	return `# BlueGit op de mini-PC. Kopieer naar /etc/bluegit/config.yml.
# Plain HTTP. TLS en de publieke SSH-poort doet de ingress, zie docs/INGRESS.md.
base_url: https://git.timfalken.com
listen: 0.0.0.0:8080
# Database, sleutel en het gekozen opslagpad. Dit is niet de datadisk.
state_path: /var/lib/bluegit
# storage_path blijft leeg. De installatiebeheerder kiest de datadisk
# bij de eerste aanmelding. Er is geen standaardpad.
# Alleen deze adressen mogen X-Forwarded-For en X-Real-IP zetten.
# Zet hier het IP van de ingress, zoals de mini-PC die verbinding ziet.
trusted_proxies:
  - 10.0.0.2

auth:
  mode: oauth
  base_url: https://auth.timfalken.com
  # Het domein is de client_id. Registreer het pad /auth/callback bij /admin.
  client_id: git.timfalken.com
  # Laat leeg en zet BLUEGIT_AUTH_CLIENT_SECRET, of gebruik client_secret_file.
  client_secret: ""
  client_secret_file: /etc/bluegit/client_secret
  redirect_path: /auth/callback
  user_agent: BlueGitAccountClient/0.1

git:
  binary: git
  default_branch: master

ssh:
  enabled: true
  # Waar dit proces git-SSH aanneemt. De SSH van het besturingssysteem blijft vrij.
  listen: 0.0.0.0:2222
  # Wat gebruikers in de clone-URL zien. De ingress stuurt poort 22 hiernaartoe.
  public_host: git.timfalken.com
  public_port: 22

runner:
  name: Steve

ci:
  enabled: true
  docker_binary: docker
  concurrency: 1
  network: bridge
  timeout_seconds: 1800
`
}
