#!/usr/bin/env bun
/**
 * Build the Shade Prekey Server Docker image locally.
 *
 * Usage:
 *   bun run build:docker              # build as shade-prekey:dev
 *   bun run build:docker -- --tag X   # custom tag
 *   bun run build:docker -- --push    # build + push to Gitea registry
 *
 * Env:
 *   GITEA_TOKEN    — required for --push
 *   GITEA_USER     — default Stian
 */
import { $ } from 'bun';

const args = process.argv.slice(2);
const tagIdx = args.indexOf('--tag');
const tag = tagIdx >= 0 ? args[tagIdx + 1] : 'dev';
const shouldPush = args.includes('--push');
const user = process.env.GITEA_USER ?? 'Stian';
const registry = 'gt.zyon.no';
const image = `${registry.toLowerCase()}/${user.toLowerCase()}/shade-prekey`;
const fullTag = `${image}:${tag}`;

async function main() {
  console.log(`Building ${fullTag}…`);
  await $`docker build -f packages/shade-server/Dockerfile -t ${fullTag} .`;

  console.log(`✓ Built ${fullTag}`);
  const { stdout: size } = await $`docker images ${fullTag} --format {{.Size}}`.quiet();
  console.log(`  Size: ${size.toString().trim()}`);

  if (shouldPush) {
    const token = process.env.GITEA_TOKEN;
    if (!token) {
      console.error('GITEA_TOKEN env var required for --push');
      process.exit(1);
    }
    console.log(`Pushing ${fullTag}…`);
    // Login via stdin to avoid leaking token in process table
    const loginProc = Bun.spawn(['docker', 'login', registry, '-u', user, '--password-stdin'], {
      stdin: 'pipe',
      stdout: 'inherit',
      stderr: 'inherit',
    });
    loginProc.stdin.write(token);
    await loginProc.stdin.end();
    await loginProc.exited;

    await $`docker push ${fullTag}`;
    console.log(`✓ Pushed ${fullTag}`);

    if (tag !== 'latest') {
      const latestTag = `${image}:latest`;
      await $`docker tag ${fullTag} ${latestTag}`;
      await $`docker push ${latestTag}`;
      console.log(`✓ Pushed ${latestTag}`);
    }
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
