// decrypt restores encrypted object-storage archives downloaded from Data Forwarding.
// It uses only the Go standard library. Run: go run decrypt.go -h
package main

import (
	"bytes"
	"compress/gzip"
	"crypto/aes"
	"crypto/cipher"
	"flag"
	"fmt"
	"io"
	"os"
)

const encryptedPrefixSize = 1024
const defaultIV = "HwJJVZtFV3Z2wtL4ZOcXh6yt2GpDovCa"

// Archive compatibility requires raw string bytes, suffix truncation, and ASCII '0' padding.
func fixedBytes(value string, size int) []byte {
	data := []byte(value)
	if len(data) >= size {
		return data[len(data)-size:]
	}
	result := bytes.Repeat([]byte{'0'}, size)
	copy(result, data)
	return result
}

func archiveIV() string {
	if value, exists := os.LookupEnv("KODO_BACKUP_IV"); exists {
		return value
	}
	return defaultIV
}

func restoreFile(inputPath, outputPath, workspace, iv string) (kind string, err error) {
	if inputPath == "" || outputPath == "" || workspace == "" {
		return "", fmt.Errorf("-in, -out, and -workspace are required")
	}
	input, err := os.Open(inputPath)
	if err != nil {
		return "", fmt.Errorf("open input: %w", err)
	}
	defer input.Close()

	prefix := make([]byte, encryptedPrefixSize)
	n, err := io.ReadFull(input, prefix)
	if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
		return "", fmt.Errorf("read encrypted prefix: %w", err)
	}
	prefix = prefix[:n]
	block, err := aes.NewCipher(fixedBytes(workspace, 32))
	if err != nil {
		return "", fmt.Errorf("initialize decryption: %w", err)
	}
	cipher.NewCTR(block, fixedBytes(iv, aes.BlockSize)).XORKeyStream(prefix, prefix)
	var restored io.Reader = io.MultiReader(bytes.NewReader(prefix), input)

	switch {
	case bytes.HasPrefix(prefix, []byte{'P', 'A', 'R', '1'}):
		// Parquet handles its own internal compression. Do not gunzip this data.
		kind = "Parquet"
	case bytes.HasPrefix(prefix, []byte{0x1f, 0x8b}):
		var reader *gzip.Reader
		reader, err = gzip.NewReader(restored)
		if err != nil {
			return "", fmt.Errorf("invalid gzip header: %w", err)
		}
		defer reader.Close()
		restored = reader
		kind = "decompressed JSON/NDJSON"
	default:
		return "", fmt.Errorf("unrecognized decrypted header: check the workspace UUID, archive-time IV, and input file")
	}

	// Exclusive creation also prevents overwriting the input or an existing symlink.
	output, err := os.OpenFile(outputPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
	if err != nil {
		return "", fmt.Errorf("create output: %w", err)
	}
	complete := false
	defer func() {
		if !complete {
			output.Close()
			if removeErr := os.Remove(outputPath); removeErr != nil && !os.IsNotExist(removeErr) {
				err = fmt.Errorf("%w; could not remove incomplete output: %v", err, removeErr)
			}
		}
	}()
	if _, err = io.Copy(output, restored); err != nil {
		return "", fmt.Errorf("restore archive: %w", err)
	}
	if err = output.Sync(); err != nil {
		return "", fmt.Errorf("flush output: %w", err)
	}
	if err = output.Close(); err != nil {
		return "", fmt.Errorf("close output: %w", err)
	}
	complete = true
	return kind, nil
}

func main() {
	input := flag.String("in", "", "Encrypted input archive (.lock.gz or .parquet.lock.gz)")
	output := flag.String("out", "", "New output path; existing files are never overwritten")
	workspace := flag.String("workspace", "", "Full UUID of the workspace that generated the archive")
	flag.Parse()
	kind, err := restoreFile(*input, *output, *workspace, archiveIV())
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error:", err)
		os.Exit(1)
	}
	fmt.Printf("Restored %s: %s\n", kind, *output)
}
