package connection

import (
	"fmt"
	"rbd_exporter/mytypes"
	"github.com/ceph/go-ceph/rados"
)

func Connect(params mytypes.Params) (_ mytypes.CephConnection, err error) {
	var cephConn = mytypes.CephConnection{}

	defer func() {
		if err != nil {
			err = fmt.Errorf("error in func connect() %w", err)
		}
	}()

	cephConn.Conn, err = rados.NewConnWithClusterAndUser("ceph", "client.admin")
	if err != nil {
		return mytypes.CephConnection{}, err
	}

	err = cephConn.Conn.ReadConfigFile(params.Config)
	if err != nil {
		return mytypes.CephConnection{}, err
	}

	err = cephConn.Conn.SetConfigOption("keyring", params.Keyring)
	if err != nil {
		return mytypes.CephConnection{}, err
	}

	err = cephConn.Conn.Connect()
	if err != nil {
		return mytypes.CephConnection{}, err
	}

	return cephConn, nil
}
