package main

import (
	"fmt"
	"os"
	"path/filepath"

	"src.opensuse.org/autogits/common"
)

func processRepositoryAction(h *common.RequestHandler) error {
	action := h.Request.Data.(common.RepositoryAction)

	if action.Repository.Name == common.DefaultGitPrj {
		h.Log("repository event %s for %s. Ignoring", common.DefaultGitPrj, action.Action)
		return nil
	}

	h.CreateRepositoryIfNotExist(action.Organization, common.DefaultGitPrj)
	h.GitExec("", "clone", "--depth", "1", action.PrjGit, common.DefaultGitPrj)

	switch action.Action {
	case "created":
		h.GitExec(common.DefaultGitPrj, "submodule", "--quiet", "add", "--depth", "1", action.Repository.Clone_Url)
		h.GitExec(common.DefaultGitPrj, "commit", "-m", "Automatic package inclusion")
		h.GitExec(common.DefaultGitPrj, "push")
	case "deleted":
		if stat, err := os.Stat(filepath.Join(h.GitPath, common.DefaultGitPrj, action.Repository.Name)); err != nil || !stat.IsDir() {
			h.Log("delete event for %s -- not in project. Ignoring", action.Repository.Name)
			return nil
		}
		h.GitExec(common.DefaultGitPrj, "rm", action.Repository.Name)
		h.GitExec(common.DefaultGitPrj, "commit", "-m", "Automatic package removal")
		h.GitExec(common.DefaultGitPrj, "push")
	default:
		return fmt.Errorf("%s: %s", "Unknown action type", action.Action)
	}

	return nil
}

func processPushAction(h *common.RequestHandler) error {
	action := h.Request.Data.(common.PushRequest)

	if action.Repository.Name == common.DefaultGitPrj {
		h.Log("push to %s -- ignoring", common.DefaultGitPrj)
		return nil
	}

	h.GitExec("", "clone", "--depth", "1", h.PrjGit, common.DefaultGitPrj)
	if stat, err := os.Stat(filepath.Join(h.GitPath, common.DefaultGitPrj, action.Repository.Name)); err != nil || !stat.IsDir() {
		return fmt.Errorf("Pushed to package that is not part of the project. Ignoring. : %v", err)
	}
	h.GitExec(common.DefaultGitPrj, "submodule", "update", "--init", "--depth", "1", "--checkout", action.Repository.Name)
	id, _ := h.GitBranchHead(filepath.Join(common.DefaultGitPrj, action.Repository.Name), action.Repository.Default_Branch)
	for _, commitId := range action.Commits {
		if commitId.Id == id {
			h.GitExec(filepath.Join(common.DefaultGitPrj, action.Repository.Name), "fetch", "--depth", "1", "origin", id)
			h.GitExec(filepath.Join(common.DefaultGitPrj, action.Repository.Name), "checkout", id)
			h.GitExec(common.DefaultGitPrj, "commit", "-a", "-m", "Automatic update via push")
			h.GitExec(common.DefaultGitPrj, "push")
			return nil
		}
	}

	h.Log("push of refs not on the main branch. ignoring.")
	return nil
}

func main() {
	var defs common.ListenDefinitions

	defs.Url = "prjgit-updater"
	defs.GitAuthor = "GiteaBot - AutoDevel"

	defs.Handlers=make(map[string]common.RequestProcessor)
	defs.Handlers[common.RequestType_Push] = processPushAction
	defs.Handlers[common.RequestType_Repository] = processRepositoryAction

	common.RequireGiteaSecretToken()
	common.StartServer(defs)
}
