package main

import (
	"flag"
	"fmt"
	"log"
	"net/url"

	"code.justin.tv/common/chitin"
	_ "code.justin.tv/common/golibs/bininfo"
	"github.com/hashicorp/consul/api"
	"golang.org/x/net/context"
)

func main() {
	flag.Parse()

	err := chitin.ExperimentalTraceProcessOptIn()
	if err != nil {
		log.Fatalf("trace enable err=%q", err)
	}

	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	ctx, err = chitin.ExperimentalTraceContext(ctx)
	if err != nil {
		log.Fatalf("chitin trace-context err=%q", err)
	}

	err = clear(ctx)
	if err != nil {
		log.Fatalf("consul clear err=%q", err)
	}
}

func clear(ctx context.Context) error {
	cfg := &api.Config{
		HttpClient: chitin.Client(ctx),
	}
	cc, err := api.NewClient(cfg)
	if err != nil {
		return err
	}

	svcs, err := cc.Agent().Services()
	if err != nil {
		return err
	}

	for id, svc := range svcs {
		log.Printf("id=%q addr=%q port=%d service=%q, tags=%q",
			id, svc.Address, svc.Port, svc.Service, fmt.Sprintf("%v", svc.Tags))
		for _, tag := range svc.Tags {
			if tag == url.QueryEscape("registration")+"="+url.QueryEscape("auto") {
				// TODO: remove only failing services
				// TODO: it would be even better if the services were purged automatically
				log.Printf("remove id=%q", id)
				err := cc.Agent().ServiceDeregister(id)
				if err != nil {
					return err
				}
				break
			}
		}
	}

	return nil
}
