#!/usr/bin/env deno

import { Eta } from "https://deno.land/x/eta@v3.1.0/src/index.ts"
import { InfisicalSDK } from "npm:@infisical/sdk"

import { Logger } from "jsr:@deno-library/logger";
const logger = new Logger();

import "jsr:@std/dotenv/load";

logger.info("Starting up Infisical SDK")

const client = new InfisicalSDK({
  siteUrl: "https://secrets.amy.mov"
});

logger.debug("Authenticating...")

await client.auth().universalAuth.login({
  clientId: Deno.env.get("INFISICAL_CLIENT_ID") || "",
  clientSecret: Deno.env.get("INFISICAL_CLIENT_SECRET") || "",
})

const projectId = Deno.env.get("INFISICAL_PROJECT_ID") || ""
logger.debug(`Authenticated! Fetching secrets for project ${projectId}`)

const allSecrets = await client.secrets().listSecrets({
  environment: "prod",
  projectId,
  recursive: true
});

logger.info(`Got ${allSecrets.secrets.length} secrets`)

const etaSecrets = Object.fromEntries(allSecrets.secrets.map(s => [s.secretKey, s.secretValue]))

const DEFAULT_INPUT_PATH = "./secrets.eta"
const DEFAULT_OUTPUT_PATH = "./secrets.pp"

const inputPath = Deno.env.get("TEMPLATE_PATH") || DEFAULT_INPUT_PATH
const outputPath = Deno.env.get("OUTPUT_PATH") || DEFAULT_OUTPUT_PATH

logger.info(`Template: ${inputPath}, Output: ${outputPath}. Rendering`)

const eta = new Eta({ varName: "it" })
const src = Deno.readTextFileSync(inputPath)
const res = eta.renderString(src, { secrets: etaSecrets, toLower: (s: string) => s.toLowerCase() })

Deno.writeTextFileSync(outputPath, res)

logger.info("Done!")