// Minimal test for the desync library.
//
// Creates a chunk from plain data, takes its content-addressed ID, round-trips
// it through the compressed storage format and verifys the ID validates.
package main

import (
	"bytes"
	"fmt"
	"os"

	"github.com/folbricht/desync"
)

func main() {
	plain := []byte("Hello from the Debian desync library autopkgtest.")

	// Build a chunk and compute its SHA512/256 content ID.
	chunk := desync.NewChunk(plain)
	id := chunk.ID()
	fmt.Printf("chunk id: %s\n", id)

	// Convert to the compressed storage format and back again.
	converters := desync.Converters{desync.Compressor{}}
	storage, err := chunk.Storage(converters)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Storage failed:", err)
		os.Exit(1)
	}

	restored, err := desync.NewChunkFromStorage(id, storage, converters, false)
	if err != nil {
		fmt.Fprintln(os.Stderr, "NewChunkFromStorage failed:", err)
		os.Exit(1)
	}

	data, err := restored.Data()
	if err != nil {
		fmt.Fprintln(os.Stderr, "Data failed:", err)
		os.Exit(1)
	}

	if !bytes.Equal(data, plain) {
		fmt.Fprintln(os.Stderr, "round-tripped data does not match original")
		os.Exit(1)
	}

	if restored.ID() != id {
		fmt.Fprintln(os.Stderr, "round-tripped chunk id does not match original")
		os.Exit(1)
	}

	fmt.Println("desync library test: chunk round trip OK")
}
