// -*- Mode: Go; indent-tabs-mode: t -*-

/*
 * Copyright (C) 2015 Canonical Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package snappy

import (
	. "gopkg.in/check.v1"
)

// systemd's testsuite
type DBusTestSuite struct {
	busName string
}

var _ = Suite(&DBusTestSuite{})

func (s *DBusTestSuite) SetUpTest(c *C) {
	s.busName = "foo.bar.baz"
}

const expectedBusPolicy = `<?xml version="1.0"?> <!--*-nxml-*-->
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
        "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">

<!--
  This file is autogenerated by snappy
-->

<busconfig>
        <policy user="root">
                <allow own="foo.bar.baz"/>
                <allow send_destination="foo.bar.baz"/>
        </policy>

        <policy context="default">
                <allow send_destination="foo.bar.baz"/>
        </policy>
</busconfig>
`

func (s *DBusTestSuite) TestGenBusPolicyFile(c *C) {
	generated, err := genBusPolicyFile(s.busName)
	c.Assert(err, IsNil)
	c.Assert(generated, Equals, expectedBusPolicy)
}

func (s *DBusTestSuite) TestGenBusPolicyFileGood(c *C) {
	goodnames := []string{
		"foo.bar",
		"foo.bar.baz",
		"foo-bar.baz",
		"foo_bar.baz",
		"foo-bar0.ba1z.q2ux.3norf",
	}

	for _, b := range goodnames {
		err := verifyBusName(b)
		c.Assert(err, IsNil)
	}
}
func (s *DBusTestSuite) TestGenBusPolicyFileBad(c *C) {
	badnames := []string{
		"",
		"foo",
		".foo",
		"foo.",
		"foo.bar.",
		".foo.bar",
		"_foo.bar",
		"-foo.bar",
		":1:234",
		"foo.bar.b@d",
	}

	for _, b := range badnames {
		err := verifyBusName(b)
		c.Assert(err, NotNil)
	}
}
