// Copyright (C) 2023 Marius Schellenberger

package key

import (
	"crypto/rand"
	"encoding/hex"
	"io"

	"git.giftfish.de/ston1th/keyctl/pkg/core"
)

const idSize = 16

func generate(size int) (buf []byte, err error) {
	buf = make([]byte, size)
	_, err = io.ReadFull(rand.Reader, buf)
	return
}

func GenerateID() (string, error) {
	id, err := generate(idSize)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(id), nil
}

func Generate(name, existing string, size int, enc core.Encoding, t core.Type) (kstore, k core.Key, err error) {
	id, err := GenerateID()
	if err != nil {
		return
	}
	var key []byte
	if existing != "" {
		key, err = hex.DecodeString(existing)
		size = len(key)
	} else if t == core.Xor {
		key, err = generate(size * 2)
	} else {
		key, err = generate(size)
	}
	if err != nil {
		return
	}
	key, err = t.Encode(key)
	if err != nil {
		return
	}
	kstore = core.Key{
		Name:     name,
		ID:       id,
		Size:     size,
		Encoding: enc,
		Type:     t,
	}
	k = kstore
	if t == core.Shamir || t == core.Xor {
		klen := len(key) / 2
		k.Key = core.Hex.EncodeToString(key[klen:])
		key = key[0:klen]
	}
	kstore.Key = enc.EncodeToString(key)
	return
}
