// Package protocol is het draadformaat tussen BlueGit en bluegit-backup.
// Het moet gelijk blijven aan internal/backup in BlueGit (docs/BACKUP.md).
package protocol

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"net/http"
	"path"
	"strconv"
	"strings"
	"time"
)

// KeyPrefix staat voor elke Backupserver-Key.
const KeyPrefix = "bgbk_"

// Koppen van een ondertekend verzoek van BlueGit.
const (
	HeaderInstance  = "X-BlueGit-Instance"
	HeaderTimestamp = "X-BlueGit-Timestamp"
	HeaderSignature = "X-BlueGit-Signature"
)

// MaxSkew is hoe ver de klokken uit elkaar mogen lopen.
const MaxSkew = 5 * time.Minute

// DBPath is het logische pad van de databasekopie.
const DBPath = "state/bluegit.db"

// Entry is één bestand in het manifest van BlueGit.
type Entry struct {
	Path   string `json:"path"`
	Size   int64  `json:"size"`
	MTime  int64  `json:"mtime"`
	Mode   uint32 `json:"mode"`
	SHA256 string `json:"sha256,omitempty"`
}

// Manifest is de volledige lijst op één moment.
type Manifest struct {
	Instance  string    `json:"instance_id"`
	CreatedAt time.Time `json:"created_at"`
	Files     []Entry   `json:"files"`
}

// Info is GET /api/v1/backup/info.
type Info struct {
	InstanceID string `json:"instance_id"`
	BaseURL    string `json:"base_url"`
	ServerURL  string `json:"server_url"`
	ServerID   string `json:"server_id"`
	HasStorage bool   `json:"has_storage"`
	// Protocol en MinProtocol zijn 0 bij een BlueGit van vóór de
	// protocolversie (dat is protocol 1).
	Protocol    int    `json:"protocol"`
	MinProtocol int    `json:"min_protocol"`
	Version     string `json:"version"`
}

// Peer geeft het protocol van BlueGit uit info.
func (i Info) Peer() Peer {
	p := Peer{Protocol: i.Protocol, MinProtocol: i.MinProtocol, Version: cleanVersion(i.Version)}
	if p.Protocol < 1 {
		p.Protocol = 1
	}
	if p.MinProtocol < 1 {
		p.MinProtocol = 1
	}
	return p
}

// SigningSecret leidt het HMAC-geheim af uit de key.
func SigningSecret(key string) string {
	s := sha256.Sum256([]byte("bluegit-backup-sign:" + key))
	return hex.EncodeToString(s[:])
}

// Signature is hex(HMAC-SHA256(secret, METHOD \n PATH \n TS \n sha256hex(body))).
func Signature(secret, method, p, ts string, body []byte) string {
	sum := sha256.Sum256(body)
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(strings.ToUpper(method) + "\n" + p + "\n" + ts + "\n" + hex.EncodeToString(sum[:])))
	return hex.EncodeToString(mac.Sum(nil))
}

// Sign zet de koppen op een uitgaand verzoek (gebruikt in tests en door
// BlueGit zelf).
func Sign(req *http.Request, secret, instance string, body []byte, now time.Time) {
	ts := strconv.FormatInt(now.Unix(), 10)
	req.Header.Set(HeaderInstance, instance)
	req.Header.Set(HeaderTimestamp, ts)
	req.Header.Set(HeaderSignature, Signature(secret, req.Method, req.URL.Path, ts, body))
}

// Verify controleert een binnenkomend ondertekend verzoek.
func Verify(r *http.Request, secret string, body []byte, now time.Time) error {
	ts := r.Header.Get(HeaderTimestamp)
	n, err := strconv.ParseInt(ts, 10, 64)
	if err != nil {
		return errors.New("timestamp ontbreekt")
	}
	d := now.Sub(time.Unix(n, 0))
	if d < 0 {
		d = -d
	}
	if d > MaxSkew {
		return errors.New("timestamp te oud of in de toekomst")
	}
	want := Signature(secret, r.Method, r.URL.Path, ts, body)
	if !hmac.Equal([]byte(want), []byte(r.Header.Get(HeaderSignature))) {
		return errors.New("handtekening klopt niet")
	}
	return nil
}

var (
	stateFiles = []string{"bluegit.db", "secret.key"}
	stateDirs  = []string{"ssh", "logos", "avatars"}
	dataDirs   = []string{"repos", "releases", "artifacts"}
)

// CleanLogical controleert een logisch pad zoals BlueGit dat doet. Een pad
// buiten de bekende mappen komt nooit in de kopie.
func CleanLogical(p string) (string, bool) {
	if p == "" || strings.Contains(p, "\\") || strings.ContainsRune(p, 0) || strings.HasPrefix(p, "/") {
		return "", false
	}
	c := path.Clean(p)
	if c != p || c == "." {
		return "", false
	}
	parts := strings.Split(c, "/")
	for _, part := range parts {
		if part == ".." || part == "." || part == "" {
			return "", false
		}
	}
	if len(parts) < 2 {
		return "", false
	}
	switch parts[0] {
	case "state":
		if len(parts) == 2 && has(stateFiles, parts[1]) {
			return c, true
		}
		if len(parts) >= 3 && has(stateDirs, parts[1]) {
			return c, true
		}
	case "data":
		if len(parts) >= 3 && has(dataDirs, parts[1]) && parts[2] != ".incoming" {
			return c, true
		}
	}
	return "", false
}

func has(list []string, v string) bool {
	for _, x := range list {
		if x == v {
			return true
		}
	}
	return false
}
