// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"github.com/gin-gonic/gin"
	"github.com/golang/glog"
	"runtime"
	"flag"
	"amuz.es/go/wiki/route"
	"amuz.es/go/wiki/util"
	"net/http"
	"github.com/flosch/pongo2"
)

var argIp = flag.String("listen_ip", "", "IP to listen on, defaults to all IPs")
var argPort = flag.Int("port", 8080, "port to listen")
var maxProcs = flag.Int("max_procs", 0, "max number of CPUs that can be used simultaneously. Less than 1 for default (number of cores).")

func main() {
	setMaxProcs()
	r := gin.Default()

	r.Use(gin.Recovery())

	r.NoRoute(func(c *gin.Context) {
		c.HTML(http.StatusOK, "page_404.tpl", pongo2.Context{})
	})

	r.StaticFS("/static", route.Static(""))

	r.GET("/api", route.Api)
	r.GET("/page", route.Page)
	r.GET("/metric", route.Metric)
	r.GET("/health", func(c *gin.Context) {
		c.String(200, "OK! - wiki services are fully operational!")
	})

	// Use pongo2gin.Default() for default options or pongo2gin.New()
	// if you need to use custom RenderOptions.
	r.HTMLRender = util.Default()
	r.GET("/", route.Index)
	r.Run() // listen and server on 0.0.0.0:8080
}

func setMaxProcs() {
	// TODO(vmarmol): Consider limiting if we have a CPU mask in effect.
	// Allow as many threads as we have cores unless the user specified a value.
	var numProcs int
	if *maxProcs < 1 {
		numProcs = runtime.NumCPU()
	} else {
		numProcs = *maxProcs
	}
	runtime.GOMAXPROCS(numProcs)

	// Check if the setting was successful.
	actualNumProcs := runtime.GOMAXPROCS(0)
	if actualNumProcs != numProcs {
		glog.Warningf("Specified max procs of %v but using %v", numProcs, actualNumProcs)
	}
}