package main

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"

	"github.com/sassoftware/go-rpmutils"
	log "github.com/sirupsen/logrus"
	"pault.ag/go/debian/deb"
)

func main() {
	for _, arg := range os.Args[1:] {
		var buf []byte
		var err error
		// XXX no all data will come from a package _file_.
		// like, from Flatcar's gentoo ebuilds. That current script just walks the /var/db/pkg/ tree for metadata
		// this may want to query local dpkg or rpm database.
		// or even a yum or debian remote repo?
		switch {
		case strings.HasSuffix(arg, ".deb"):
			buf, err = getDebInfo(arg)
		case strings.HasSuffix(arg, ".rpm"):
			buf, err = getRPMInfo(arg)
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(string(buf))
	}
}

func getRPMInfo(rpmfile string) ([]byte, error) {
	f, err := os.Open(rpmfile)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	rpm, err := rpmutils.ReadRpm(f)
	if err != nil {
		return nil, err
	}
	nevra, err := rpm.Header.GetNEVRA()
	if err != nil {
		return nil, err
	}

	return json.MarshalIndent(nevra, "", "  ")
}

func getDebInfo(debfile string) ([]byte, error) {
	d, cl, err := deb.LoadFile(debfile)
	if err != nil {
		return nil, err
	}
	defer cl()

	return json.MarshalIndent(d.Control, "", "  ")
}
