#!/usr/bin/python3

import os
import shutil
import tempfile
from textwrap import dedent
import unittest

from .systemd_clickhook import (
    CLICK_OWNED_PREFIX,
    Path,
    update_systemd_units,
)


def touch(f):
    with open(f, "w"):
        pass


class UbuntuAppDaemonUpdateTestCase(unittest.TestCase):

    def setUp(self):
        self.temp_dir = tempfile.mkdtemp()
        os.makedirs(self.temp_dir + Path.SRC_DIR)
        os.makedirs(self.temp_dir + Path.DEST_DIR)
        Path.SRC_DIR = self.temp_dir + Path.SRC_DIR
        Path.DEST_DIR = self.temp_dir + Path.DEST_DIR
        Path.SYSTEMCTL = "/bin/true"

    def tearDown(self):
        shutil.rmtree(self.temp_dir)

    def test_update(self):
        prefix = CLICK_OWNED_PREFIX
        self.make_installed_click("app-existing")
        # create one existing
        touch(os.path.join(
            Path.DEST_DIR,
            "%scom.example.app-existing_app_1.0.service" % prefix))
        os.symlink(os.path.join(self.temp_dir, "opt", "click.ubuntu.com",
                                "app-existing", "1.0", "data",
                                "app-existing.service"),
                   os.path.join(Path.SRC_DIR,
                                "com.example.app-existing_app_1.0.service"))
        # one new
        self.make_installed_click("app-new")
        os.symlink(os.path.join(self.temp_dir, "opt", "click.ubuntu.com",
                                "app-new", "1.0", "data",
                                "app-new.service"),
                   os.path.join(Path.SRC_DIR,
                                "com.example.app-new_app_1.0.service"))
        # one old
        touch(os.path.join(
            Path.DEST_DIR, "%scom.example.app_old_1.0.service" % prefix))

        # run it
        update_systemd_units()

        # verify
        self.assertEqual(
            set(["%scom.example.app-existing_app_1.0.service" % prefix,
                 "%scom.example.app-new_app_1.0.service.service" % prefix]),
            set(os.listdir(Path.DEST_DIR)))
        service_file = os.path.join(
            Path.DEST_DIR,
            "%scom.example.app-new_app_1.0.service.service" % prefix)
        with open(service_file) as f:
                self.assertTrue(self.temp_dir in f.read())

    def make_installed_click(self, name, version="1.0"):
        basedir = os.path.join(
            self.temp_dir, "opt", "click.ubuntu.com", name, version)
        # info dir for the click
        os.makedirs(os.path.join(basedir, ".click", "info"))
        touch(os.path.join(
            basedir, ".click", "info", "com.example.%s.manifest" % name))
        # name of the dir does not matter
        os.makedirs(os.path.join(basedir, "data"))
        with open(os.path.join(basedir, "data", name+".service"), "w") as f:
            f.write(dedent("""\
            [Unit]
            Description=Hello example service
            [Service]
            ExecStart=${CLICK_PACKAGE_PATH}/bin/hello-daemon
            Restart=on-failure
            [Install]
            WantedBy=multi-user.target
            """))


if __name__ == "__main__":
    import logging
    logging.basicConfig(level=logging.DEBUG)
    unittest.main()
