package main

import (
	"fmt"
	"log"
	"math/rand"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/gorilla/context"
	"github.com/kelseyhightower/envconfig"
	"github.com/spf13/cobra"
	"s.mcquay.me/dm/hdx"
)

type Config struct {
	Host   string
	Port   int
	DBHost string
	DBName string
	DBUser string
}

func init() {
	rand.Seed(time.Now().UnixNano())
}

func main() {
	var host string
	var port int

	var run = &cobra.Command{
		Use:   "run",
		Short: "run command",
		Long:  `run hdxd with given options`,
		Run: func(cmd *cobra.Command, args []string) {
			config := &Config{
				DBHost: "localhost",
				DBName: "hdx",
				DBUser: "dm",
			}
			err := envconfig.Process("hdxd", config)
			if err != nil {
				log.Fatal(err)
			}
			if host != "" {
				config.Host = host
			}
			if port != -1 {
				config.Port = port
			} else {
				if config.Port == 0 {
					config.Port = 8080
				}
			}
			log.Printf("%+v", config)

			sigs := make(chan os.Signal, 1)
			signal.Notify(sigs, os.Interrupt, os.Kill)
			go func() {
				s := <-sigs
				log.Printf("signal: %+v", s)
				os.Exit(1)
			}()

			sm := http.NewServeMux()
			_, err = hdx.NewServer(
				sm,
				config.DBHost,
				config.DBName,
				config.DBUser,
				"",
			)
			if err != nil {
				log.Fatalf("problem initializing hdxd server: %+v", err)
			}

			hostname := "localhost"
			if config.Host == "" {
				hostname, err = os.Hostname()
				if err != nil {
					log.Printf("problem getting hostname:", err)
				}
			}
			log.Printf("serving at: http://%s:%d/", hostname, config.Port)

			addr := fmt.Sprintf("%s:%d", config.Host, config.Port)
			err = http.ListenAndServe(addr, context.ClearHandler(sm))
			if err != nil {
				log.Printf("%+v", err)
				os.Exit(1)
			}
		},
	}

	run.Flags().StringVarP(
		&host,
		"host",
		"n",
		"",
		"hostname",
	)
	run.Flags().IntVarP(
		&port,
		"port",
		"p",
		-1,
		"port",
	)

	var rootCmd = &cobra.Command{Use: "app"}
	rootCmd.AddCommand(run)
	rootCmd.Execute()
}
