import { getEnv } from "../../util/env.js";
import { regEx } from "../../util/regex.js";
import { logger } from "../../logger/index.js";
import { decrypt, isSupportedRuntime } from "@renovatebot/pgp";

//#region lib/config/decrypt/bcpgp.ts
async function tryDecryptBcPgp(privateKey, encryptedStr) {
	try {
		const startBlock = "-----BEGIN PGP MESSAGE-----\n\n";
		const endBlock = "\n-----END PGP MESSAGE-----";
		let armoredMessage = encryptedStr.trim();
		const hasStartHeader = armoredMessage.startsWith(startBlock);
		const hasEndHeader = armoredMessage.endsWith(endBlock);
		if (!hasStartHeader && !hasEndHeader && !armoredMessage.includes("=") && !armoredMessage.includes("\n") && armoredMessage.length % 4 !== 0) {
			logger.debug("Adding base64 padding to armored message");
			armoredMessage += `=`.repeat(4 - armoredMessage.length % 4);
		}
		// v8 ignore else -- TODO: add test #40625
		if (!hasStartHeader) armoredMessage = `${startBlock}${armoredMessage}`;
		// v8 ignore else -- TODO: add test #40625
		if (!hasEndHeader) armoredMessage = `${armoredMessage}${endBlock}`;
		const data = await decrypt(privateKey.replace(regEx(/\n[ \t]+/g), "\n"), armoredMessage, { runtime: runtime() });
		logger.debug("Decrypted config using bcpgp");
		return data;
	} catch (err) {
		logger.debug({ err }, "Could not decrypt using bcpgp");
		return null;
	}
}
function runtime() {
	const runtime = getEnv().RENOVATE_X_PGP_RUNTIME;
	if (runtime) if (isSupportedRuntime(runtime)) {
		logger.trace({ runtime }, "Using configured PGP runtime");
		return runtime;
	} else logger.once.warn({ runtime }, "Unknown PGP runtime, using wasm-java");
	logger.trace("Using default PGP runtime: wasm-java");
	return "wasm-java";
}

//#endregion
export { tryDecryptBcPgp };
//# sourceMappingURL=bcpgp.js.map