//go:generate go-bindata -pkg bundled -o pkg/bundled/bindata.go pvt-www/...
package main

import (
	"flag"
	"fmt"
	"os"

	gophertype "git.kirsle.net/apps/gophertype/pkg"
	"git.kirsle.net/apps/gophertype/pkg/console"
	_ "git.kirsle.net/apps/gophertype/pkg/controllers"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
)

// Build parameters.
var (
	Build     string
	BuildDate string
)

// Command-line flags.
var (
	optVersion bool
	optDebug   bool
	optBind    string
	optRoot    string

	// Database option flags.
	optSQLite   string
	optPostgres string
	optMySQL    string

	// Chosen DB options.
	dbDriver string
	dbPath   string
)

func init() {
	flag.BoolVar(&optVersion, "version", false, "Show version number and exit")
	flag.BoolVar(&optVersion, "v", false, "Show version number and exit (alias)")
	flag.BoolVar(&optDebug, "debug", false, "Debug level logging")
	flag.StringVar(&optBind, "bind", ":8000", "Bind address for HTTP server")
	flag.StringVar(&optRoot, "root", "./public_html", "User root for custom web pages")

	// Database driver. Choose one.
	flag.StringVar(&optSQLite, "sqlite3", "", "Use SQLite database, default 'database.sqlite'")
	flag.StringVar(&optPostgres, "postgres", "",
		"Use Postgres database, format: "+
			"host=myhost port=myport user=gorm dbname=gorm password=mypassword")
	flag.StringVar(&optMySQL, "mysql", "",
		"Use MySQL database, format: "+
			"user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
}

func main() {
	flag.Parse()

	if optVersion {
		fmt.Printf("This is gophertype v%s build %s (built on %s)\n", gophertype.Version, Build, BuildDate)
		os.Exit(0)
	}

	console.SetDebug(optDebug)

	// Validate the choice of database.
	if optSQLite != "" {
		dbDriver = "sqlite3"
		dbPath = optSQLite
	} else if optPostgres != "" {
		dbDriver = "postgres"
		dbPath = optPostgres
	} else if optMySQL != "" {
		dbDriver = "mysql"
		dbPath = optMySQL
	} else {
		fmt.Print(
			"Choose a database to use when running this command. Examples:\n" +
				"gophertype -sqlite3 database.sqlite\n" +
				"gophertype -postgres host=myhost port=myport user=gorm dbname=gorm password=mypassword\n" +
				"gophertype -mysql user:password@/dbname?charset=utf8&parseTime=True&loc=Local",
		)
		os.Exit(1)
	}

	app := gophertype.NewSite(optRoot)
	if err := app.UseDB(dbDriver, dbPath); err != nil {
		panic(err)
	}
	app.SetupRouter()

	// Set up the Redis connection if available/enabled.
	app.SetupRedis()

	if err := app.ListenAndServe(optBind); err != nil {
		console.Error("ListenAndServe: %s", err)
		os.Exit(0)
	}
}
