package main

import (
	"database/sql"
	"os"
	"path/filepath"
	"runtime"

	"github.com/coder/coder/v2/coderd/database/dbtestutil"
	"github.com/coder/coder/v2/coderd/database/migrations"
)

var preamble = []byte("-- Code generated by 'make coderd/database/generate'. DO NOT EDIT.")

func main() {
	connection, closeFn, err := dbtestutil.Open()
	if err != nil {
		panic(err)
	}
	defer closeFn()

	db, err := sql.Open("postgres", connection)
	if err != nil {
		panic(err)
	}
	defer db.Close()

	err = migrations.Up(db)
	if err != nil {
		panic(err)
	}

	dumpBytes, err := dbtestutil.PGDumpSchemaOnly(connection)
	if err != nil {
		panic(err)
	}

	_, mainPath, _, ok := runtime.Caller(0)
	if !ok {
		panic("couldn't get caller path")
	}
	err = os.WriteFile(filepath.Join(mainPath, "..", "..", "..", "dump.sql"), append(preamble, dumpBytes...), 0o600)
	if err != nil {
		panic(err)
	}
}
