// This file is part of the adequate Debian-native package, and is available
// under the Expat license. For the full terms please see debian/copyright.

package main

import (
	"fmt"
	"log"
	"os"
	"regexp"
)

const MISSING_COPYRIGHT_FILE_TAG = "missing-copyright-file"

type missingCopyrightErr struct {
	pkg  string
	path string
	err  error
}

var (
	archAwarePackageNameRE *regexp.Regexp = regexp.MustCompile("([^:]+)(:?:.*)?")
)

func (m missingCopyrightErr) Error() string {
	if m == (missingCopyrightErr{}) {
		return ""
	}
	if m.err != nil {
		return fmt.Sprintf("%q: %s %v\n", m.pkg, MISSING_COPYRIGHT_FILE_TAG, m.err)
	}
	return fmt.Sprintf("%s: %s %s", m.pkg, MISSING_COPYRIGHT_FILE_TAG, m.path)
}

type copyrightChecker struct {
	emit bool
}

func newCopyrightChecker(tags tagFilter) copyrightChecker {
	return copyrightChecker{
		emit: tags.shouldEmit(MISSING_COPYRIGHT_FILE_TAG),
	}
}

func (cc copyrightChecker) check(pkgs []string) []error {
	if !cc.emit {
		return nil
	}
	var errs []error
	for _, pkg := range pkgs {
		if err := cc.isOkay(pkg); err != (missingCopyrightErr{}) {
			errs = append(errs, err)
		}
	}
	return errs
}

func (cc copyrightChecker) isOkay(pkg string) missingCopyrightErr {
	p, ok := copyrightFileExists(pkg)
	if !ok {
		return missingCopyrightErr{
			pkg:  pkg,
			path: p,
		}
	}

	return missingCopyrightErr{}
}

// copyrightFileExists returns the expected path to the copyright file for a
// given binary package and whether it exists. It does not attempt to
// distinguish between whether a file is missing or we get an error while trying
// to determine so.
func copyrightFileExists(pkg string) (string, bool) {
	m := archAwarePackageNameRE.FindStringSubmatch(pkg)
	if len(m) < 2 {
		log.Fatalf("Unexpected package name: %q", pkg)
	}
	noArchPkg := m[1]
	p := fmt.Sprintf("/usr/share/doc/%s/copyright", noArchPkg)
	_, err := os.Stat(p)
	return p, err == nil
}
