package main

import (
	// External
	"git.gibonuddevalla.se/go/dbschema"
	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"

	// Standard
	"fmt"
	"os"
)

var (
	db *sqlx.DB
)

func sqlCallback(dbname string, version int) (sql []byte, found bool) {
	fname := fmt.Sprintf("sql/%04d.sql", version)

	var err error
	sql, err = sqlFS.ReadFile(fname)
	if err != nil {
		if !os.IsNotExist(err) {
			logger.Error("database", "error", err)
		}
		return
	}

	found = true
	return
}

func logCallback(topic, details string) {
	logger.Info("database", topic, details)
}

func initDB() (err error) { // {{{
	dbConn := fmt.Sprintf(
		"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		config.Database.Host,
		config.Database.Port,
		config.Database.Username,
		config.Database.Password,
		config.Database.Db,
	)

	logger.Info(
		"database",
		"host", config.Database.Host,
		"port", config.Database.Port,
	)

	if db, err = sqlx.Connect("postgres", dbConn); err != nil {
		return
	}

	upgrader := dbschema.NewUpgrader()
	upgrader.SetSqlCallback(sqlCallback)
	upgrader.SetLogCallback(logCallback)
	_, err = upgrader.AddDatabase(
		config.Database.Host,
		config.Database.Port,
		config.Database.Db,
		config.Database.Username,
		config.Database.Password,
	)
	if err != nil {
		return
	}
	err = upgrader.Run()

	return
} // }}}
