package backup

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

// Koppen van een ondertekend verzoek tussen BlueGit en de backup server.
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

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

// Sign zet de koppen op een uitgaand verzoek. body is wat er verstuurd wordt.
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
}
