package main

import (
	"fmt"
	"log"
	"regexp"
	"strings"
)

const MISSING_PKGCONF_DEPENDENCY_TAG = "missing-pkgconfig-dependency"

type pkgconfErr struct {
	debPkg     string
	pkg        string
	missingDep string
}

func (p pkgconfErr) Error() string {
	return fmt.Sprintf("%s: %s %s => %s", p.debPkg, MISSING_PKGCONF_DEPENDENCY_TAG, p.pkg, p.missingDep)
}

type pkgconfDepChecker struct {
	emit bool
}

func newPkgconfDepChecker(tags tagFilter) pkgconfDepChecker {
	return pkgconfDepChecker{
		emit: tags.shouldEmit(MISSING_PKGCONF_DEPENDENCY_TAG),
	}
}

func (pd pkgconfDepChecker) check(pkg2files map[string][]string) []pkgconfErr {
	if !pd.emit || !pathExists("/usr/bin/pkgconf") {
		return nil
	}

	ignorePath := regexp.MustCompile("^/usr/(?:share|lib(?:/[^/]+)?)/pkgconfig/([^/]+)[.]pc$")
	// pkgs maps from a pc name to a binary package name. The pc name
	// maps to a source package but does not necessarily match the source
	// package name.
	pkgs := make(map[string]string)
	for debPkg, files := range pkg2files {
		for _, f := range files {
			m := ignorePath.FindStringSubmatch(f)
			if len(m) < 2 {
				continue
			}
			pkg := m[1]
			pkgs[pkg] = debPkg
		}
	}

	var tags []pkgconfErr
	for pkg, debPkg := range pkgs {
		out, err := runCommand(append(strings.Split("pkgconf --exists --print-errors", " "), pkg))
		/* $ pkgconf --exists --print-errors gtk-engines-2
		Package gtk+-2.0 was not found in the pkg-config search path.
		Perhaps you should add the directory containing `gtk+-2.0.pc'
		to the PKG_CONFIG_PATH environment variable
		Package 'gtk+-2.0', required by 'gtk-engines-2', not found
		*/
		if err == nil {
			continue
		}

		missingPkg := regexp.MustCompile("Package '(.+)', required by '" + pkg + "', not found")
		m := missingPkg.FindStringSubmatch(strings.Join(out, " "))
		if len(m) < 2 {
			log.Fatalf("Unexpected pkgconf output: %v", out)
		}
		depPkg := m[1]
		tags = append(tags, pkgconfErr{
			debPkg:     debPkg,
			pkg:        pkg,
			missingDep: string(depPkg),
		})
	}

	return tags
}
