package main

import (
	"os"

	"go.wit.com/dev/alexflint/arg"
	"go.wit.com/lib/protobuf/forgepb"
	"go.wit.com/lib/protobuf/gitpb"
	"go.wit.com/log"
)

// sent via -ldflags
var VERSION string
var BUILDTIME string

var pp *arg.Parser
var forge *forgepb.Forge

var workingRepo *gitpb.Repo

func main() {
	log.Info("go-clone version", VERSION, "built on", BUILDTIME)
	pp = arg.MustParse(&argv)

	// for very new users or users unfamilar with the command line, this may help them
	if argv.Repo == "help" || argv.Repo == "?" {
		pp.WriteHelp(os.Stdout)
		os.Exit(0)
	}
	if argv.Repo == "version" {
		log.Info(argv.Version())
		os.Exit(0)
	}

	// this package helps scan git repos
	forge = forgepb.Init()

	var err error
	// attempt to clone, returns *gitpb.Repo
	workingRepo, err = clone(argv.Repo)
	if err != nil {
		badExit(err)
	}
	if argv.Recursive {
		log.Info("STARTING RECURSIVE CLONE", workingRepo.GetGoPath())
		if err := recursiveClone(workingRepo); err != nil {
			badExit(err)
		}
	}
	autoWork()
	if argv.Build {
		log.Info("STARTING BUILD", workingRepo.GetGoPath())
		/*
			if err := makeValidGoSum(workingRepo); err != nil {
				badExit(err)
			}
			if err := build(); err != nil {
				badExit(err)
			}
		*/
		if workingRepo.GetRepoType() == "binary" || workingRepo.GetRepoType() == "plugin" {
			log.Info("build will probably fail", workingRepo.GetGoPath(), "is", workingRepo.GetRepoType())
		}
		if err := forge.Build(workingRepo, nil); err != nil {
			log.Warn("BUILD FAILED", workingRepo.GetGoPath(), err)
			badExit(err)
		}
	}
	if argv.Install {
		log.Info("STARTING INSTALL", workingRepo.GetGoPath())
		// can only install binary or plugin go packages
		if workingRepo.GetRepoType() == "binary" || workingRepo.GetRepoType() == "plugin" {
			log.Info("install will probably fail", workingRepo.GetGoPath(), "is", workingRepo.GetRepoType())
		}
		if err := forge.Install(workingRepo, nil); err != nil {
			log.Warn("INSTALL FAILED", workingRepo.GetGoPath(), err)
			badExit(err)
		}
	}
	okExit("")
}

func okExit(thing string) {
	if thing != "" {
		log.Info(thing, "ok")
	}
	log.Info("Finished clone on", workingRepo.GetGoPath(), "ok")
	forge.ConfigSave()
	os.Exit(0)
}

func badExit(err error) {
	log.Info("Total repositories:", forge.Repos.Len())
	log.Info("Finished go-clone with error", err, forge.GetGoSrc())
	os.Exit(-1)
}