// 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 (
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"os/exec"
	"slices"
	"strings"
	"syscall"
)

var (
	allPkgs      = flag.Bool("all", false, "check all installed packages")
	selectedTags = flag.String("tags", "", "comma-separated list of tags to emit; "+
		"prefix with a - to specify tags not to emit; defaults to emitting all tags")
	root           = flag.String("root", "", "switch root directory")
	user           = flag.String("user", "", "--user <user>[:<group>]  switch user and group")
	help           = flag.Bool("help", false, "display help and exit")
	version        = flag.Bool("version", false, "display version and exit")
	listTags       = flag.Bool("list-tags", false, "list all tag names and exit")
	aptPreinstMode = flag.Bool("apt-preinst", false, "(used internally by the APT hook)")
	pendingMode    = flag.Bool("pending", false, "(used internally by the APT hook)")
	debconf        = flag.Bool("debconf", false, "report issues via debconf")
	failMode       = flag.Bool("fail", false, "exit with non-zero code if at least "+
		"one package failed at least one check; ignored when --debconf is set")
)

func main() {
	flag.Usage = func() { printUsage(); os.Exit(1) } // called on invalid invocation
	flag.Parse()
	if err := checkArgs(flag.Args()); err != nil {
		fmt.Println(err.Error())
		flag.Usage()
	}

	pkgs := flag.Args()
	var ignoreMissingPackages bool
	switch {
	case *help:
		printUsage()
		os.Exit(0)
	case *version:
		fmt.Printf("adequate %s\n", adequateVersion)
		return
	case *listTags:
		fmt.Println(strings.Join(knownTags(), "\n"))
		return
	case *debconf && !*pendingMode:
		log.Fatal("--debconf is only supported with --pending")
	case *aptPreinstMode:
		stdinReader := aptHookReader()

		switch {
		case *root != "":
			log.Fatal("--apt-preinst and --root cannot be used together")
		case *allPkgs:
			log.Fatal("--apt-preinst and --all cannot be used together")
		case *pendingMode:
			log.Fatal("--apt-preinst and --pending cannot be used together")
		case len(flag.Args()) > 0:
			log.Fatalf("Too many arguments")
		case !aptHookIsEnabled(stdinReader):
			return
		}
		ph, err := newPendingHandler()
		if err != nil {
			log.Fatal(err.Error())
		}
		defer ph.cleanupOrDie()

		pkgs = readPkgs(stdinReader)
		ph.writePendingOrDie(pkgs)
		return
	case *pendingMode:
		if !slices.Contains(os.Environ(), "DEBIAN_HAS_FRONTEND=1") {

			args := []string{"-oadequate", "--", "/usr/bin/adequate",
				"--pending", "--debconf"}
			if *user != "" {
				args = append(args, []string{"--user", *user}...)
			}
			cmd := &exec.Cmd{
				Path:   "/usr/bin/debconf",
				Args:   args,
				Stdin:  os.Stdin,
				Stdout: os.Stdout,
				Stderr: os.Stdout,
				SysProcAttr: &syscall.SysProcAttr{
					Setsid:  true,
					Setctty: true,
				},
			}
			if err := cmd.Run(); err != nil {
				// This is typically due to stdout not being an
				// interactive terminal.
				fmt.Fprintf(os.Stderr, "adequate: failed to run debconf frontend: %v\n", err)
			}
			os.Exit(0)
		}

		ph, err := newPendingHandler()
		if err != nil {
			log.Fatal(err.Error())
		}
		defer ph.cleanupOrDie()
		defer ph.truncatePendingOrDie()

		pkgs, err = ph.read()
		if err != nil {
			log.Fatalf("Failed to read %s: %v", pendingPath, err)
		}
		if len(pkgs) == 0 {
			return
		}
		ignoreMissingPackages = true
	case len(pkgs) == 0 && !*allPkgs:
		log.Fatal("No packages to check.")
	case len(pkgs) > 0 && *allPkgs:
		log.Fatal("Too many arguments.")
	case len(invalidPkgs(pkgs)) > 0:
		log.Fatal("Invalid package name(s): ", strings.Join(invalidPkgs(pkgs), " "))
	}

	ids, err := newLDDids(*user)
	if err != nil {
		log.Fatalf(err.Error())
	}

	chroot(*root)

	tags, err := newTagFilter(*selectedTags)
	if err != nil {
		log.Fatalf("Invalid --tags value(s): %s", err)
	}

	pkgProvides := packageProvides(ignoreMissingPackages, pkgs)
	for p := range pkgProvides {
		pkgs = append(pkgs, p)
	}

	pkgFiles, err := packageFiles(pkgs)
	if err != nil {
		log.Fatal("Failed to get package files: ", err)
	}

	if err := os.Setenv("LC_ALL", "C"); err != nil {
		log.Fatal("Failed to set LC_ALL: ", err)
	}

	s := sink{seen: make(map[string]bool)}
	s.add(mapTags(newBrokenSymlinkChecker(tags).check(pkgFiles)))
	s.add(mapTags(newCollisionChecker(tags).check(pkgFiles)))
	s.add(mapTags(newCopyrightChecker(tags).check(pkgs)))
	s.add(mapTags(newPackageConffileChecker(tags).check(pkgs)))
	s.add(mapTags(newPkgconfDepChecker(tags).check(pkgFiles)))
	s.add(mapTags(newPyfileChecker(tags).check(pkgFiles)))
	s.add(mapTags(newAltChecker(tags).check(pkgProvides, pkgFiles)))
	s.add(mapTags(newBinfmtChecker(tags).check(pkgFiles)))
	s.add(mapTags(newElfChecker(tags, ids).check(pkgFiles)))

	if s.empty() {
		os.Exit(0)
	}

	if *debconf {
		tellDebconf(s.tags)
	} else {
		for _, t := range s.tags {
			fmt.Println(t)
		}
		if *failMode {
			os.Exit(2)
		}
	}

}

func mapTags[T error](errs []T) []string {
	var strs []string
	for _, e := range errs {
		strs = append(strs, e.Error())
	}
	return strs
}

type sink struct {
	seen map[string]bool
	tags []string
}

func (s *sink) add(tags []string) {
	for _, t := range tags {
		if s.seen[t] {
			continue
		}
		s.tags = append(s.tags, t)
		s.seen[t] = true
	}
}

func (s *sink) empty() bool {
	return len(s.tags) == 0
}

func chroot(dir string) {
	if dir == "" {
		return
	}
	if err := syscall.Chroot(dir); err != nil {
		log.Fatalf("chroot failed: %v", err)
	}
}

func printUsage() {
	fmt.Println(`Usage:

  adequate [options] <package-name>...
  adequate [options] --all
  adequate [options] --apt-preinst
  adequate [options] --pending
  adequate --help

Options:`)
	// Make PrintDefaults() print to stdout and not return with
	// non-zero status (which the adequate apt hook relies on).
	flag.CommandLine.SetOutput(os.Stdout)
	flag.PrintDefaults()
}

func invalidPkgs(pkgs []string) []string {
	var inv []string
	for _, p := range pkgs {
		if strings.HasPrefix(p, "--") {
			inv = append(inv, p)
		}
	}
	return inv
}

func checkArgs(args []string) error {
	flagMode := true
	for _, a := range args {
		if flagMode && a[0] != '-' {
			flagMode = false
		} else if !flagMode && a[0] == '-' {
			return errors.New("command line options must appear before packages")
		}
	}
	return nil
}

const adequateVersion = "dummy-adequate-version"
