// Command sign-checksums is a CI helper that signs a file using minisign.
//
// The minisign CLI reads passwords from /dev/tty, which doesn't exist in CI
// runners. This program uses the library directly: password and encrypted
// secret key come from environment variables, no terminal required.
//
// Usage (in CI):
//
//	MINISIGN_SECRET_KEY=... MINISIGN_PASSWORD=... go run ./tools/sign-checksums dist/sha256sums.txt
//
// Produces dist/sha256sums.txt.minisig alongside the input.
package main

import (
	"fmt"
	"os"

	"aead.dev/minisign"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "usage: sign-checksums <file>\n")
		os.Exit(2)
	}
	filePath := os.Args[1]

	password := os.Getenv("MINISIGN_PASSWORD")
	keyBytes := []byte(os.Getenv("MINISIGN_SECRET_KEY"))
	if len(keyBytes) == 0 {
		fmt.Fprintln(os.Stderr, "MINISIGN_SECRET_KEY is not set")
		os.Exit(1)
	}

	key, err := minisign.DecryptKey(password, keyBytes)
	if err != nil {
		fmt.Fprintf(os.Stderr, "decrypt key: %v\n", err)
		os.Exit(1)
	}

	message, err := os.ReadFile(filePath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "read %s: %v\n", filePath, err)
		os.Exit(1)
	}

	sig := minisign.Sign(key, message)
	sigPath := filePath + ".minisig"
	if err := os.WriteFile(sigPath, sig, 0644); err != nil {
		fmt.Fprintf(os.Stderr, "write %s: %v\n", sigPath, err)
		os.Exit(1)
	}
	fmt.Printf("signed %s -> %s\n", filePath, sigPath)
}
