package main

import (
	"context"
	"os"

	"dagger.io/dagger"
)

func Upload(ctx context.Context) error {
	client, err := dagger.Connect(ctx, dagger.WithLogOutput(os.Stdout))
	if err != nil {
		return err
	}

	src := client.Host().
		Directory("bench_app/", dagger.HostDirectoryOpts{Exclude: []string{"target/"}})

	rust_base := client.Container().
		From("rustlang/rust:nightly").
		WithDirectory("/mnt/app", src).
		WithWorkdir("/mnt/app").
		WithExec([]string{"cargo", "build", "--release"})

	rust_binary := rust_base.File("target/release/bench_app")

	rust_application_image := client.
		Container().
		From("debian:bullseye-slim").
		WithFile("/usr/bin/bench_app", rust_binary).
		WithExec([]string{"/usr/bin/bench_app", "-h"})

	wasm_binary := client.Container().
		From("rustlang/rust:nightly").
		WithExec([]string{"rustup", "target", "add", "wasm32-wasi"}).
		WithDirectory("/mnt/app", src).
		WithWorkdir("/mnt/app").
		WithExec([]string{"cargo", "build", "--release", "--target=wasm32-wasi"}).
		File("target/wasm32-wasi/release/bench_app.wasm")

	_, err = rust_binary.Export(ctx, "dist/binary/bench_app")
	if err != nil {
		return err
	}

	_, err = wasm_binary.Export(ctx, "dist/wasm/bench_app.wasm")
	if err != nil {
		return err
	}

	imagetag, err := rust_application_image.Publish(
		ctx,
		"kasperhermansen/dagger-runtime-benchmark:latest",
	)
	if err != nil {
		return err
	}
	println(imagetag)

	return nil
}
