// 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 (
	"os"
	"path"
	"strings"
	"testing"
)

func TestConfffileParsing(t *testing.T) {
	pkgs := []string{"aide-common", "alsa-topology-conf", "alsa-ucm-conf",
		"alsa-utils", "anacron"}

	fakeRunner := func([]string) ([]string, error) {
		// /etc/default/duplicate is owned by both alsa-utils (not
		// obsolete) and anacron (obsolete). Non-duplicate obsolete
		// entries must be handled by stubReader() below.
		return strings.Split(`aide-common,aide-common

alsa-topology-conf,alsa-topology-conf

alsa-ucm-conf,alsa-ucm-conf

alsa-utils,alsa-utils
 /etc/init.d/alsa-utils c52e669945e1b6c4b77e00cefa21073a
 /etc/default/duplicate 964d39a52b30de6627ba346001730f03
anacron,anacron
 /etc/anacrontab 00ff43422e8756204113c5546b00d529
 /etc/cron.d/anacron 389b4ee27d3023ec855897c16612f319 obsolete
 /etc/cron.daily/0anacron a46c5cc26a2a6715d0155781ddd07a19
 /etc/cron.monthly/0anacron 402ac7af3ebd2da5dddcd3712d776ae3
 /etc/cron.weekly/0anacron b2c55b2905f28b3b53bdf3e2d66e830b obsolete
 /etc/default/duplicate 964d39a52b30de6627ba346001730f03 obsolete`, "\n"), nil
	}

	stubReader := func(f string) ([]byte, error) {
		// Should only be called for obsolete marked files, excluding
		// duplicates one of which is not obsolete. That is:
		// /etc/cron.d/anacron and /etc/cron.weekly/0anacron.
		b, err := os.ReadFile("testdata/" + path.Base(f))
		if err != nil {
			t.Fatal("Test setup failure: stubReader() called for ", f)
		}
		return b, nil
	}

	got := packageConffileChecker{
		dqFunc:   fakeRunner,
		readFile: stubReader,
		emit:     true}.check(pkgs)

	// /etc/cron.d/anacron and /etc/cron.d/0weekly are obsolete, but the
	// latter has been modified so expected a tag to be emitted only for the
	// former.
	want := []conffileErr{{
		pkg:  "anacron",
		path: "/etc/cron.d/anacron",
	}}

	// TODO: use cmp.Diff instead.
	if len(got) != len(want) {
		t.Errorf("Want %d tags, got %d", len(want), len(got))
	}
	if len(got) > 0 && got[0] != want[0] {
		t.Errorf("Got: %#v\nWant: %#v\n", got, want)
	}
}
