package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"time"
)

func main() {

	today := 0
	if len(os.Args) > 2 {
		today = 1
	}

	type CVE_Json struct {
		CVEDataType         string `json:"CVE_data_type"`
		CVEDataFormat       string `json:"CVE_data_format"`
		CVEDataVersion      string `json:"CVE_data_version"`
		CVEDataNumberOfCVEs string `json:"CVE_data_numberOfCVEs"`
		CVEDataTimestamp    string `json:"CVE_data_timestamp"`
		CVEItems            []struct {
			Cve struct {
				DataType    string `json:"data_type"`
				DataFormat  string `json:"data_format"`
				DataVersion string `json:"data_version"`
				CVEDataMeta struct {
					ID       string `json:"ID"`
					ASSIGNER string `json:"ASSIGNER"`
				} `json:"CVE_data_meta"`
				Problemtype struct {
					ProblemtypeData []struct {
						Description []struct {
							Lang  string `json:"lang"`
							Value string `json:"value"`
						} `json:"description"`
					} `json:"problemtype_data"`
				} `json:"problemtype"`
				References struct {
					ReferenceData []struct {
						URL       string   `json:"url"`
						Name      string   `json:"name"`
						Refsource string   `json:"refsource"`
						Tags      []string `json:"tags"`
					} `json:"reference_data"`
				} `json:"references"`
				Description struct {
					DescriptionData []struct {
						Lang  string `json:"lang"`
						Value string `json:"value"`
					} `json:"description_data"`
				} `json:"description"`
			} `json:"cve"`
			Configurations struct {
				CVEDataVersion string `json:"CVE_data_version"`
				Nodes          []struct {
					Operator string `json:"operator"`
					CpeMatch []struct {
						Vulnerable          bool   `json:"vulnerable"`
						Cpe23URI            string `json:"cpe23Uri"`
						VersionEndExcluding string `json:"versionEndExcluding"`
					} `json:"cpe_match"`
				} `json:"nodes"`
			} `json:"configurations"`
			Impact struct {
				BaseMetricV3 struct {
					CvssV3 struct {
						Version               string  `json:"version"`
						VectorString          string  `json:"vectorString"`
						AttackVector          string  `json:"attackVector"`
						AttackComplexity      string  `json:"attackComplexity"`
						PrivilegesRequired    string  `json:"privilegesRequired"`
						UserInteraction       string  `json:"userInteraction"`
						Scope                 string  `json:"scope"`
						ConfidentialityImpact string  `json:"confidentialityImpact"`
						IntegrityImpact       string  `json:"integrityImpact"`
						AvailabilityImpact    string  `json:"availabilityImpact"`
						BaseScore             float64 `json:"baseScore"`
						BaseSeverity          string  `json:"baseSeverity"`
					} `json:"cvssV3"`
					ExploitabilityScore float64 `json:"exploitabilityScore"`
					ImpactScore         float64 `json:"impactScore"`
				} `json:"baseMetricV3"`
				BaseMetricV2 struct {
					CvssV2 struct {
						Version               string  `json:"version"`
						VectorString          string  `json:"vectorString"`
						AccessVector          string  `json:"accessVector"`
						AccessComplexity      string  `json:"accessComplexity"`
						Authentication        string  `json:"authentication"`
						ConfidentialityImpact string  `json:"confidentialityImpact"`
						IntegrityImpact       string  `json:"integrityImpact"`
						AvailabilityImpact    string  `json:"availabilityImpact"`
						BaseScore             float64 `json:"baseScore"`
					} `json:"cvssV2"`
					Severity                string  `json:"severity"`
					ExploitabilityScore     float64 `json:"exploitabilityScore"`
					ImpactScore             float64 `json:"impactScore"`
					AcInsufInfo             bool    `json:"acInsufInfo"`
					ObtainAllPrivilege      bool    `json:"obtainAllPrivilege"`
					ObtainUserPrivilege     bool    `json:"obtainUserPrivilege"`
					ObtainOtherPrivilege    bool    `json:"obtainOtherPrivilege"`
					UserInteractionRequired bool    `json:"userInteractionRequired"`
				} `json:"baseMetricV2"`
			} `json:"impact"`
			PublishedDate    string `json:"publishedDate"`
			LastModifiedDate string `json:"lastModifiedDate"`
		} `json:"CVE_Items"`
	}
	file, _ := ioutil.ReadFile(os.Args[1])
	data := CVE_Json{}
	_ = json.Unmarshal([]byte(file), &data)
	//	fmt.Println("error:", _err, _err.Error())

	type CVE struct {
		Title         string    `json:"Title"`
		ID            string    `json:"id"`
		Descr         string    `json:"descr"`
		BaseScoreV2   string    `json:"basescorev2"`
		BaseScoreV3   string    `json:"basescorev3"`
		SeverityV2    string    `json:"severityv2"`
		SeverityV3    string    `json:"severityv3"`
		NvdURL        string    `json:"nvdurl"`
		DebianURL     string    `json:"Debianurl"`
		RHURL         string    `json:"rhdurl"`
		UbuntuURL     string    `json:"ubuntuurl"`
		ModifiedDate  time.Time `json:modifieddate`
		PublishedDate time.Time `json:publisheddate`
		//Age           string    `json:age`
	}

	const layout = "2006-01-02T15:04Z"
	dt := time.Now().Add(-24 * time.Hour * 3)
	//loc, _ := time.LoadLocation("UTC")
	//now := time.Now().In(loc)
	for _, v := range data.CVEItems {
		md, err := time.Parse(layout, v.LastModifiedDate)
		if err != nil {
			fmt.Println("Error", err.Error())
		}
		pd, _err := time.Parse(layout, v.PublishedDate)
		//		fmt.Println(time.Date(pd.Year(), pd.Month(), pd.Day(), 0, 0, 0, 0, pd.Location()))
		//		if time.Date(pd.Year(), pd.Month(), pd.Day(), 0, 0, 0, 0, pd.Location()) != time.Date(time.Now().AddDate(0, 0, -1).Year(), time.Now().AddDate(0, 0, -1).Month(), time.Now().AddDate(0, 0, -1).Day(), 0, 0, 0, 0, time.Now().AddDate(0, 0, -1).Location()) || time.Date(md.Year(), md.Month(), md.Day(), 0, 0, 0, 0, md.Location()) != time.Date(time.Now().AddDate(0, 0, -1).Year(), time.Now().AddDate(0, 0, -1).Month(), time.Now().AddDate(0, 0, -1).Day(), 0, 0, 0, 0, time.Now().AddDate(0, 0, -1).Location()) {
		if pd.Year() < 2020 {
			if today == 1 {
				continue
			}
		}
		if pd.Before(dt) && md.Before(dt) {
			if today == 1 {
				continue
			}
		}
		if _err != nil {
			fmt.Println("Error", err.Error())
		}
		cve := CVE{}

		if v.Impact.BaseMetricV2.CvssV2.BaseScore < 1 && v.Impact.BaseMetricV3.CvssV3.BaseScore < 1 {
			continue
		}
		for _, x := range v.Cve.Description.DescriptionData {
			cve.Descr = x.Value
			break
		}
		cve.ModifiedDate = md
		cve.PublishedDate = pd
		cve.ID = v.Cve.CVEDataMeta.ID
		cve.BaseScoreV2 = fmt.Sprintf("%f", v.Impact.BaseMetricV2.CvssV2.BaseScore)
		cve.BaseScoreV3 = fmt.Sprintf("%f", v.Impact.BaseMetricV3.CvssV3.BaseScore)
		cve.SeverityV2 = v.Impact.BaseMetricV2.Severity
		cve.SeverityV3 = v.Impact.BaseMetricV3.CvssV3.BaseSeverity
		cve.NvdURL = "https://nvd.nist.gov/vuln/detail/" + cve.ID
		cve.DebianURL = "https://security-tracker.debian.org/tracker/" + cve.ID
		cve.RHURL = "https://bugzilla.redhat.com/show_bug.cgi?id=" + cve.ID
		cve.UbuntuURL = "https://ubuntu.com/security/" + cve.ID
		//		cve.Age = md.String()

		data, _ := json.MarshalIndent(cve, " ", "")
		fmt.Println(string(data))

	}

}
