/* SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only */
/* Copyright (c) 2024-2025 Brett Sheffield <bacs@librecast.net> */

#ifndef _KEY_H
#define _KEY_H 1
#include <agent.h>
#include <librecast/key.h>
#include <sodium.h>
#include <stdint.h>
#include <stdio.h>

#define KEY_AUTH_FILE "authorized_keys"
#define KEY_CAP_DEFAULT_SECONDS 0 /* never expire */

/* decode hex keyring */
int key_combo_hex_decode(key_combo_t *keyring);

/* extract public encryption key from combo hex key */
int key_combo_hex2pek(unsigned char *pek, size_t len, char *phex_combo);

/* extract public signing key from combo hex key */
int key_combo_hex2psk(unsigned char *psk, size_t len, char *phex_combo);

/* extract secret encryption key from combo hex key */
int key_combo_hex2sek(unsigned char *sek, size_t len, char *shex_combo);

/* extract secret signing key from combo hex key */
int key_combo_hex2ssk(unsigned char *ssk, size_t len, char *shex_combo);

/* generate encryption + signing keys */
int key_gen_keys(key_combo_t *keyring);

/* generate combo keypair, convert to hex */
int key_gen_combopair_hex(key_combo_t *keyring);

/* generate keypair, write into directory */
int key_gen_combopair_write(char *home, key_combo_t *keyring);

/* load default key, or create one */
int key_load_default(state_t *state, key_combo_t *keyring);

char *key_config_dir(char *home, size_t *len);

#if 0
int key_cap_sign(unsigned char *cap, size_t len, unsigned char *s_auth, unsigned char *p_bear,
		uint8_t capbits, char *res);
#endif

/* flags to pass to key_cap_issue */
enum {
	KEY_CAP_SAVE = 0x1,
	KEY_CAP_SEND = 0x2,
	KEY_CAP_PATH = 0x4, /* print path to cap */
};

/* return pathname for channel hash. free() after use */
char *key_cap_path(state_t *state, unsigned char *chanhash, size_t len);

int key_cap_load(lc_token_t *token, state_t *state, unsigned char *chanhash, size_t len);

int key_cap_issue(state_t *state, lc_keypair_t *signing_key, uint8_t *bearer_key,
	lc_channel_t *chan, uint8_t capbits, uint64_t valid_sec, int flags);

int keyring_add(state_t *state, char *hexkey);
int keyring_del(state_t *state, char *hexkey);
int keyring_show(state_t *state);
int keyring_load(state_t *state, lc_keyring_t *keyring);
void keyring_freekeys(lc_keyring_t *keyring);

#endif /* _KEY_H */
