package tasks

import (
	"fmt"
	"sec-cycle-scan/common"
	"sec-cycle-scan/service"
	"sec-cycle-scan/utils"
	"time"
)

func SecretTask() {

	common.LOG.Info("The secret key detection task has started execution.")

	orgList := common.CONFIG.Gitleaks.OrgList

	for _, org := range orgList {

		repoCount, err := service.GetRepoCount(org)
		if err != nil {
			common.LOG.Error(fmt.Sprintf("Failed to retrieve the number of GitHub repositories. org:%s err:%s", org, err))
			continue
		}

		repoList, err := service.GetRepoList(org, repoCount)
		if err != nil {
			common.LOG.Error(fmt.Sprintf("Failed to fetch repositories. org:%s err:%s", org, err))
			continue
		}

		for _, repo := range repoList {

			if repo.Visibility == "private" || repo.Visibility == "" {
				continue
			}

			common.LOG.Info(fmt.Sprintf("The repository %s has started the key scanning process.", repo.FullName))
			time.Sleep(5 * time.Second)
			assetStr, codeDir := utils.CalculateCodeDir(repo)
			if err = service.SecretScan(repo, codeDir, assetStr); err != nil {
				common.LOG.Error(fmt.Sprintf("Secret scanning failed. repo: %s  err: %s", repo.FullName, err))
			}
		}
	}
}
