package core

import (
	"fmt"
	"os"
	"path/filepath"
)

// embedStubs maps embedded stub filenames to their empty content.
var embedStubs = map[string]string{
	"embedded_pubkey.go": `// Code generated by necropolis generate. DO NOT EDIT.
package core

var embeddedOperatorPubKey = []byte{}
`,
	"embedded_implant_key.go": `// Code generated by necropolis generate. DO NOT EDIT.
package core

var embeddedImplantPrivKey = []byte{}
`,
	"embedded_boxpubkey.go": `// Code generated by necropolis generate. DO NOT EDIT.
package core

var embeddedOperatorBoxPubKey = []byte{}
`,
	"embedded_authtoken.go": `// Code generated by necropolis generate. DO NOT EDIT.
package core

var embeddedAuthToken = []byte{}
`,
}

// backupStubs saves the current embedded stub files in the given coreDir
// and overwrites them with empty content so the temp-dir build can proceed.
// Returns a restore function.
func backupStubs(coreDir string) func() {
	backups := make(map[string][]byte)
	for name := range embedStubs {
		path := filepath.Join(coreDir, name)
		if data, err := os.ReadFile(path); err == nil {
			backups[name] = data
		}
	}
	return func() {
		for name, data := range backups {
			os.WriteFile(filepath.Join(coreDir, name), data, 0644)
		}
	}
}

// writeEmbeddedCreds writes the real operator credentials into the embedded
// stub files in the implant source tree, replacing the empty stubs.
func writeEmbeddedCreds(coreDir string, pub, box, priv, auth []byte) {
	pubLiteral := bytesLiteral(pub)
	boxLiteral := bytesLiteral(box)
	privLiteral := bytesLiteral(priv)
	authLiteral := bytesLiteral(auth)

	os.WriteFile(filepath.Join(coreDir, "embedded_pubkey.go"), []byte(fmt.Sprintf(
		"// Code generated by necropolis generate. DO NOT EDIT.\npackage core\n\nvar embeddedOperatorPubKey = %s\n",
		pubLiteral)), 0644)
	os.WriteFile(filepath.Join(coreDir, "embedded_boxpubkey.go"), []byte(fmt.Sprintf(
		"// Code generated by necropolis generate. DO NOT EDIT.\npackage core\n\nvar embeddedOperatorBoxPubKey = %s\n",
		boxLiteral)), 0644)
	os.WriteFile(filepath.Join(coreDir, "embedded_implant_key.go"), []byte(fmt.Sprintf(
		"// Code generated by necropolis generate. DO NOT EDIT.\npackage core\n\nvar embeddedImplantPrivKey = %s\n",
		privLiteral)), 0644)
	os.WriteFile(filepath.Join(coreDir, "embedded_authtoken.go"), []byte(fmt.Sprintf(
		"// Code generated by necropolis generate. DO NOT EDIT.\npackage core\n\nvar embeddedAuthToken = %s\n",
		authLiteral)), 0644)
}
