//go:build !noSign

package license

import (
	"encoding/json"
	"fmt"

	"github.com/hyperboloide/lk"
)

// Sign marshals a licence and signs it, returning the base32 blob.
//
// This file carries the !noSign build tag so the signing path can be compiled
// out of the control plane. The server has no reason to hold signing code and
// no reason to ship it into a customer's data centre.
//
// privateKeyB32 comes from LICENSE_SIGNING_KEY on the issuing side only.
func Sign(l License, privateKeyB32 string) (string, error) {
	if privateKeyB32 == "" {
		return "", fmt.Errorf("no signing key provided")
	}
	priv, err := lk.PrivateKeyFromB32String(privateKeyB32)
	if err != nil {
		return "", fmt.Errorf("parse signing key: %w", err)
	}

	data, err := json.Marshal(l)
	if err != nil {
		return "", fmt.Errorf("marshal licence: %w", err)
	}

	signed, err := lk.NewLicense(priv, data)
	if err != nil {
		return "", fmt.Errorf("sign licence: %w", err)
	}

	blob, err := signed.ToB32String()
	if err != nil {
		return "", fmt.Errorf("encode licence: %w", err)
	}
	return blob, nil
}
