// Copyright (C) 2018-2023  Nexedi SA and Contributors.
//                          Kirill Smelkov <kirr@nexedi.com>
//
// This program is free software: you can Use, Study, Modify and Redistribute
// it under the terms of the GNU General Public License version 3, or (at your
// option) any later version, as published by the Free Software Foundation.
//
// You can also Link and Combine this program with other software covered by
// the terms of any of the Free Software licenses or any of the Open Source
// Initiative approved licenses and Convey the resulting work. Corresponding
// source of such a combination shall include the source code for all other
// software used.
//
// This program is distributed WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// See COPYING file for full licensing terms.
// See https://www.nexedi.com/licensing for rationale and options.

package neonet
// joining raw underlying network.

import (
	"context"
	"fmt"
	"strings"

	"lab.nexedi.com/kirr/go123/xerr"
	"lab.nexedi.com/kirr/go123/xnet"
	"lab.nexedi.com/kirr/go123/xnet/lonet"
	"lab.nexedi.com/kirr/go123/xstrings"

	"lab.nexedi.com/kirr/neo/go/neo/internal/xpath/xfilepath"
	"lab.nexedi.com/kirr/neo/go/neo/internal/xtls"
)


// Config specifies network configuration for Join.
//
// Empty config means to use plain TCP networking for inter-node exchange.
type Config struct {
	// CA/Cert/Key, if non-empty, tells to use TLS in peer-to-peer mode
	// with CA certificate and public/private node keys taken from specified files.
	CA, Cert, Key string

	// LoNode, if non-empty, tells to use lonet as underlying network.
	// Network and hostname should be specified as "<net>/<host>".
	LoNode string
}


// Join returns network access-point suitable for interoperating with nodes in
// a NEO cluster according to config.
func Join(ctx context.Context, cfg Config) (net xnet.Networker, err error) {
	optv := []string{}
	ssl := (cfg.CA != "" || cfg.Cert != "" || cfg.Key != "")
	if ssl {
		optv = append(optv, "ssl")
	}
	if cfg.LoNode != "" {
		optv = append(optv, fmt.Sprintf("lonode=%q", cfg.LoNode))
	}
	defer xerr.Contextf(&err, "neonet join [%s]", strings.Join(optv, " "))

	if ssl && !(cfg.CA != "" && cfg.Cert != "" && cfg.Key != "") {
		return nil, fmt.Errorf("incomplete ca/cert/key provided")
	}

	defer func() {
		if err != nil && net != nil {
			net.Close() // ignore err
		}
	}()

	if cfg.LoNode == "" {
		net = xnet.NetPlain("tcp") // TODO not only "tcp" ?
	} else {
		netname, hostname, err := xstrings.HeadTail(cfg.LoNode, "/")
		if err != nil {
			return nil, fmt.Errorf("invalid lonode")
		}
		network, err := lonet.Join(ctx, netname)
		if err != nil {
			return nil, err
		}
		host, err := network.NewHost(ctx, hostname)
		if err != nil {
			network.Close() // ignore err
			return nil, err
		}
		network.AutoClose() // host.Close will close network

		net = host
	}

	if ssl {
		xu := xfilepath.ExpandUser // Expand user for compatibility with NEO/py:
		//	https://lab.nexedi.com/nexedi/neoppod/blob/d5afef8e/neo/lib/config.py#L149
		//	https://lab.nexedi.com/nexedi/neoppod/blob/d5afef8e/neo/lib/app.py#L25-31
		tlsCfg, err := xtls.ConfigForP2P(xu(cfg.CA), xu(cfg.Cert), xu(cfg.Key))
		if err != nil {
			return nil, err
		}
		net = xnet.NetTLS(net, tlsCfg)
	}

	return net, nil
}
