// Package wireguard implements a few helpers for the WireGuard protocol
package wireguard

import (
	"errors"

	"codeberg.org/eduVPN/eduvpn-common/internal/wireguard/ini"
	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)

// Config places a WireGuard key `key` inside of the WireGuard config `cfg`
func Config(cfg string, key *wgtypes.Key) (string, error) {
	// the key is nil if the client does not accept WireGuard
	if key == nil {
		return "", errors.New("the server sent us a WireGuard profile but the client does not accept WireGuard")
	}

	// first parse the config
	secs := ini.Parse(cfg)
	if secs.Empty() {
		return "", errors.New("parsed ini is empty")
	}

	// find the interface section
	// and set the private key
	is, err := secs.Section("Interface")
	if err != nil {
		return "", err
	}
	is.AddOrReplaceKeyValue("PrivateKey", key.String())
	return secs.String(), nil
}
