package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/exec"

	"golang.org/x/oauth2"

	"github.com/stvp/rollbar"
	"github.com/zenazn/goji"
	"github.com/zenazn/goji/web"
	"golang.org/x/net/context"

	"code.justin.tv/common/chitin"
	"code.justin.tv/common/golibs/statsd"
	"code.justin.tv/release/forge/internal/terraform"
	"code.justin.tv/release/forge/internal/util"
	"code.justin.tv/release/libforerunner"
	"code.justin.tv/release/twitchstats"
)

var (
	// GitCommit is set at build time to the current git commit for the project.
	GitCommit = "development"
	c         *Config
	fr        *libforerunner.Forerunner

	oauthConfig  *oauth2.Config
	statsdClient statsd.Stats
	mixpanel     *twitchstats.Stats
)

type Config struct {
	ConsulPrefix   string `description:"Prefix for consul data storage"`
	Environment    string `description:"Environment skadi is running in"`
	GithubAPIToken string `forerunner:"github-api-token" description:"Token for talking to github api"`
	MixpanelToken  string `forerunner:",secret" description:"Token for talking to Mixpanel"`
	PgConnInfo     string `description:"Connection string for postgres"`
	Port           int    `description:"Port to bind to for HTTP API"`
	RollbarToken   string `forerunner:",secret" description:"Token for talking to rollbar"`
	StatsdHost     string `description:"Host to send statsd data to"`
	StatsdPort     int    `description:"Port to send statsd data to"`
	StatsdPrefix   string `description:"Prefix for statsd metrics"`
}

func init() {
	var err error

	terraformVersion, terraformCommit, err := terraform.Version()
	if err != nil {
		log.Fatal(err)
	}

	// Setup the default configuration
	c = &Config{
		ConsulPrefix:  "application-data/forge/dev",
		Environment:   "development",
		MixpanelToken: "XXXXXXXXXX", // The token for the staging mixpanel.
		PgConnInfo:    "sslmode=disable",
		Port:          8080,
		RollbarToken:  "XXXXXXXXXX",
		StatsdHost:    "graphite.internal.justin.tv",
		StatsdPort:    8125,
		StatsdPrefix:  "forge.development",
	}
	fr, err = libforerunner.Init(&libforerunner.Options{
		DefaultConfig: c,
	})
	if err != nil {
		log.Fatal(err)
	}

	err = fr.GetConfig(c)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Fprintf(os.Stderr, "Running commit %q, terraform %q [%v] with config:\n", GitCommit, terraformVersion, terraformCommit)
	fr.Print()

	// Initialize the oauth2 config
	oauthConfig = &oauth2.Config{
		ClientID:     "XXXXXXXXXX",
		ClientSecret: "XXXXXXXXXX",
		Scopes:       []string{"user:email"},
		Endpoint: oauth2.Endpoint{
			AuthURL: "https://git-aws.internal.justin.tv/login/oauth/authorize",
		},
		RedirectURL: "http://localhost:8000/github_callback",
	}

	// Setup the statsd client
	statsdClient = util.MustSetupStatsd(c.StatsdHost, c.StatsdPort, c.StatsdPrefix)

	// Setup the mixpanel client
	mixpanel = &twitchstats.Stats{
		MixPanelToken: c.MixpanelToken,
	}
	mixpanel.Client = chitin.Client(context.Background())
	mixpanel.Verbose = true
	mixpanel.Add("system", "forge")
	mixpanel.Add("system_version", GitCommit)
	mixpanel.Add("system_env", c.Environment)
	mixpanel.Add("terraform_version", terraformVersion)
	mixpanel.Add("terraform_commit", terraformCommit)

	// Configure Rollbar
	rollbar.Token = c.RollbarToken
	rollbar.Environment = c.Environment
	rollbar.CodeVersion = GitCommit
}

func whoami(c web.C, w http.ResponseWriter, r *http.Request) {
	whoami, err := exec.Command("whoami").Output()
	if err != nil {
		log.Fatal(err)
	}
	io.WriteString(w, string(whoami))
}

func main() {
	InitializeApi()

	goji.Handle("/*", http.FileServer(http.Dir("assets")))
	goji.Serve()
}
