#!/usr/bin/perl

use warnings;
use strict;

use Cwd qw(getcwd);
use File::Slurp;
use File::stat;
use Test::More;

chdir($ENV{AUTOPKGTEST_TMP}) or die "chdir: $!\n";

sub assert_present {
	my ($name) = @_;
	ok(-d "/home/e-$name");
	ok(-f "/home/e-$name/ikiwiki.setup");
	ok(-f "/home/e-$name/public_html/ikiwiki/index.html");

	my $uid = getpwnam("e-$name");
	my $stat = stat("/home/e-$name");
	is($stat->uid, $uid);
}

sub assert_absent {
	my ($name) = @_;
	ok(! -e "/home/e-$name");
}

# This assumes that ikiwiki-hosting.conf still has prefix_e=example.com.
ok(! system(qw(ikisite create foo.example.com --admin=root@localhost)));
assert_present('foo');

my $backup = $ENV{AUTOPKGTEST_TMP}.'/backup';

ok(! system(qw(ikisite backup), '--filename='.$backup, qw(foo.example.com)));
ok(! system(qw(ikisite compact foo.example.com)));
ok(! system(qw(ikisite rename foo.example.com baz.example.com)));
ok(! system(qw(ikisite restore foo.example.com), '--filename='.$backup));
ok(! system(qw(ikisite branch foo.example.com bar.example.com)));

ok(! system('getent passwd "$(id -nu)" > passwd'));
ok(! system('getent group "$(id -ng)" > group'));
write_file('hosts', <<EOF);
127.0.0.1 foo.example.com
EOF

$ENV{NSS_WRAPPER_PASSWD} = getcwd.'/passwd';
$ENV{NSS_WRAPPER_GROUP} = getcwd.'/group';
$ENV{NSS_WRAPPER_HOSTS} = getcwd.'/hosts';

SKIP: {
	# This only tests systemd, because we can't easily tell the
	# difference between sysv-rc and a chroot/container with no init
	# system at all
	skip('init system not necessarily running', 5) unless -d '/run/systemd/system';

	ok(! system(qw(ikisite changesetup --enable-plugin=branchable --set branchable=1 foo.example.com)));
	ok(! system(qw(systemctl status ikiwiki-hosting-web.service)));

	{
		local $ENV{LD_PRELOAD} = 'libnss_wrapper.so';
		ok(! system(qw(git clone git://foo.example.com/source.git)));
	}

	ok(! system('find source -name .git -prune -o -print >&2'));
	ok(-f 'source/.gitignore')
};

ok(! system(qw(ikisite delete foo.example.com)));
ok(! system(qw(ikisite delete bar.example.com)));
ok(! system(qw(ikisite delete baz.example.com)));
assert_absent('foo');
assert_absent('bar');
assert_absent('baz');

done_testing;
