package main

import (
	"flag"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"0xacab.org/meskio/cicer/api"
	"github.com/gorilla/mux"
	"github.com/olivere/env"
)

type handler struct {
	assets string
}

func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	path, err := filepath.Abs(r.URL.Path)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	path = filepath.Join(h.assets, path)
	_, err = os.Stat(path)
	if os.IsNotExist(err) {
		http.ServeFile(w, r, h.assets)
		return
	} else if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	http.FileServer(http.Dir(h.assets)).ServeHTTP(w, r)
}

func main() {
	var (
		dbPath  = flag.String("db-path", env.String("./test.db", "DB_PATH"), "Path where the sqlite will be located {DB_PATH}")
		addr    = flag.String("addr", env.String(":8080", "HTTP_ADDR", "ADDR"), "Address where the http server will bind {HTTP_ADDR}")
		signKey = flag.String("signkey", env.String("", "SIGNKEY"), "Sign key for authentication tokens. DO NOT LEAVE UNSET!!! {SIGNKEY}")
		assets  = flag.String("assets", env.String("./build", "ASSETS_PATH"), "Path to the assets (js, html, ...) {ASSETS_PATH}")
	)
	flag.Parse()
	log.Println("listening in address:", *addr)

	r := mux.NewRouter()
	apiRouter := r.PathPrefix("/api/").Subrouter()
	err := api.Init(*dbPath, *signKey, apiRouter)
	if err != nil {
		log.Panicln("Can't open the database:", err)
	}

	log.Println("assets:", *assets)
	h := handler{*assets}
	r.PathPrefix("/").Handler(h)
	log.Fatal(http.ListenAndServe(*addr, r))
}