#!/bin/sh
set -u

# Unit tests for scripts/functions

TEST_DIR="${0%/*}"
ROOT_DIR="$TEST_DIR/.."
CR="
"

oneTimeSetUp() {
	. "$ROOT_DIR/scripts/functions"
}

HOSTS_FOOTER="
# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters"

test_generate_hosts_content_with_domain() {
	hosts_content=$(_generate_hosts_content example com)
	assertEquals "127.0.0.1	localhost${CR}127.0.1.1	example.com	example${CR}${HOSTS_FOOTER}" "$hosts_content"
}

test_generate_hosts_content_without_domain() {
	hosts_content=$(_generate_hosts_content example "")
	assertEquals "127.0.0.1	localhost${CR}127.0.1.1	example${CR}${HOSTS_FOOTER}" "$hosts_content"
}

test_netinfo_to_resolv_conf_IPv4() {
	resolv_conf=$(netinfo_to_resolv_conf - "$TEST_DIR/netinfo/net-eth0.conf")
	assertEquals "domain example.net${CR}nameserver 192.0.2.42${CR}search example.net. example.com." "$resolv_conf"
}

test_netinfo_to_resolv_conf_duplicates() {
	resolv_conf=$(netinfo_to_resolv_conf - "$TEST_DIR/netinfo/net-eth0.conf" "$TEST_DIR/netinfo/net-eth0.conf")
	assertEquals "domain example.net${CR}nameserver 192.0.2.42${CR}search example.net. example.com." "$resolv_conf"
}

test_netinfo_to_resolv_conf_mutliple() {
	resolv_conf=$(netinfo_to_resolv_conf - "$TEST_DIR/netinfo/net-eth0.conf" "$TEST_DIR/netinfo/net-eth1.conf")
	assertEquals "domain example.org${CR}nameserver 192.0.2.42${CR}nameserver 192.0.2.84${CR}search example.net. example.com. example.org." "$resolv_conf"
}

test_netinfo_to_resolv_conf_write_output() {
	tmpfile=$(mktemp -t initramfs-tools.XXXXXXXXXX)
	netinfo_to_resolv_conf "$tmpfile" "$TEST_DIR/netinfo/net-eth0.conf"
	assertEquals "domain example.net${CR}nameserver 192.0.2.42${CR}search example.net. example.com." "$(cat "$tmpfile")"
	rm -f "$tmpfile"
}

# Load shUnit2.
. shunit2
