package udisks

import (
	"fmt"

	"github.com/godbus/dbus/v5"
)

// Unlock unlocks a LUKS device with a passphrase and returns the cleartext device.
func (c *Client) Unlock(dev *BlockDevice, passphrase string) (*BlockDevice, error) {
	obj := c.conn.Object(busName, dev.ObjectPath)

	var cleartextPath dbus.ObjectPath
	err := obj.Call(ifaceEncrypted+".Unlock", 0, passphrase, noOptions()).Store(&cleartextPath)
	if err != nil {
		return nil, fmt.Errorf("unlocking %s: %w", dev.DevicePath, err)
	}

	return c.DeviceAtPath(cleartextPath)
}

// UnlockWithKeyfile unlocks a LUKS device with keyfile contents.
func (c *Client) UnlockWithKeyfile(dev *BlockDevice, keyContents []byte) (*BlockDevice, error) {
	obj := c.conn.Object(busName, dev.ObjectPath)

	options := map[string]dbus.Variant{
		"keyfile_contents": dbus.MakeVariant(keyContents),
	}

	var cleartextPath dbus.ObjectPath
	err := obj.Call(ifaceEncrypted+".Unlock", 0, "", options).Store(&cleartextPath)
	if err != nil {
		return nil, fmt.Errorf("unlocking %s with keyfile: %w", dev.DevicePath, err)
	}

	return c.DeviceAtPath(cleartextPath)
}

// Lock locks a LUKS device.
func (c *Client) Lock(dev *BlockDevice) error {
	obj := c.conn.Object(busName, dev.ObjectPath)
	return obj.Call(ifaceEncrypted+".Lock", 0, noOptions()).Err
}
