// ucspi -- UCSPI-related utilities
// Copyright (C) 2021-2026 Sergey Matveev <stargrave@stargrave.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package ucspi

import (
	"crypto/x509"
	"encoding/pem"
	"errors"
	"os"
)

func CertificateFromFile(p string) (b []byte, c *x509.Certificate, err error) {
	var data []byte
	data, err = os.ReadFile(p)
	if err != nil {
		return
	}
	var block *pem.Block
	for len(data) > 0 {
		block, data = pem.Decode(data)
		if block == nil {
			continue
		}
		if block.Type == "CERTIFICATE" {
			b = block.Bytes
			c, err = x509.ParseCertificate(b)
			return
		}
	}
	err = errors.New("no CERTIFICATE found in PEM")
	return
}

func PrivateKeyFromFile(p string) (prv interface{}, err error) {
	var data []byte
	data, err = os.ReadFile(p)
	if err != nil {
		return
	}
	var block *pem.Block
	for len(data) > 0 {
		block, data = pem.Decode(data)
		if block == nil {
			continue
		}
		switch block.Type {
		case "PRIVATE KEY":
			prv, err = x509.ParsePKCS8PrivateKey(block.Bytes)
			return
		case "EC PRIVATE KEY":
			prv, err = x509.ParseECPrivateKey(block.Bytes)
			return
		}
	}
	err = errors.New("no PRIVATE KEY found in PEM")
	return
}

func CertPoolFromFile(p string) (certs []*x509.Certificate, pool *x509.CertPool, err error) {
	var data []byte
	data, err = os.ReadFile(p)
	if err != nil {
		return
	}
	pool = x509.NewCertPool()
	var block *pem.Block
	for len(data) > 0 {
		block, data = pem.Decode(data)
		if block == nil {
			err = errors.New("can not decode PEM")
			return
		}
		if block.Type != "CERTIFICATE" {
			err = errors.New("non CERTIFICATE found in PEM")
			return
		}
		var ca *x509.Certificate
		ca, err = x509.ParseCertificate(block.Bytes)
		if err != nil {
			return
		}
		certs = append(certs, ca)
		pool.AddCert(ca)
	}
	return
}
