package main

import (
	"log"
	"net/http"

	"git.xeserv.us/xena/route/proto/route"
	"github.com/hashicorp/terraform/helper/schema"
	"github.com/hashicorp/terraform/plugin"
	"github.com/hashicorp/terraform/terraform"
)

func main() {
	plugin.Serve(&plugin.ServeOpts{
		ProviderFunc: provider,
	})
}

// provider returns a terraform.ResourceProvider.
func provider() terraform.ResourceProvider {
	return &schema.Provider{
		Schema: map[string]*schema.Schema{
			"token": &schema.Schema{
				Type:        schema.TypeString,
				Optional:    true,
				DefaultFunc: schema.EnvDefaultFunc("ROUTE_TOKEN", nil),
			},
			"host": &schema.Schema{
				Type:        schema.TypeString,
				Optional:    false,
				Required:    true,
				DefaultFunc: schema.EnvDefaultFunc("ROUTE_HOST", nil),
			},
		},

		ResourcesMap: map[string]*schema.Resource{
			"route_route": routeResource(),
			"route_token": tokenResource(),
		},

		ConfigureFunc: providerConfigure,
	}
}

func providerConfigure(d *schema.ResourceData) (interface{}, error) {
	token := d.Get("token").(string)
	host := d.Get("host").(string)

	log.Printf("[INFO] Initializing route client connecting to %s", host)

	cl := route.New(host, token, &http.Client{})

	return cl, nil
}
