#!/usr/bin/env python3

import copy
import os
import subprocess
import sys
import unittest

FIXTURES = os.path.join(os.getcwd(), "tests/fixtures")


def executeAndReturnOutput(command, env={}):
    p = subprocess.Popen(
        command,
        encoding="utf-8",
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        env=env,
    )
    stdoutdata, stderrdata = p.communicate()
    print(stdoutdata, file=sys.stdout)
    print(stderrdata, file=sys.stderr)
    return p.returncode, stdoutdata, stderrdata


command = ["./ngcp-site"]


class TestSite(unittest.TestCase):
    def setUp(self):
        self.command = copy.deepcopy(command)

    def _testOk(self, name, site):
        self.env = {
            "NGCP_ROOT": os.path.join(FIXTURES, name),
        }
        res = executeAndReturnOutput(self.command, self.env)
        self.assertEqual(res[0], 0)
        self.assertRegex(res[1], site)
        self.assertEqual(res[2], "")

    def testNone(self):
        self._testOk("site-current-none", "none")

    def testGood(self):
        self._testOk("site-current-good", "cloud")

    def _testFail(self, name, code, error):
        self.env = {
            "NGCP_ROOT": os.path.join(FIXTURES, name),
        }
        res = executeAndReturnOutput(self.command, self.env)
        self.assertEqual(res[0], code)
        self.assertEqual(res[1], "")
        self.assertRegex(res[2], "error: " + error)

    def testNotSymlink(self):
        self._testFail(
            "site-current-file", 1, "current site .* is not a symlink"
        )

    def testNotBare(self):
        self._testFail(
            "site-current-absolute",
            2,
            "site .* is not a bare relative symlink",
        )

    def testIsDangling(self):
        self._testFail("site-current-dangling", 3, "dangling site .* symlink")

    def testIsNotDir(self):
        self._testFail(
            "site-current-notdir",
            4,
            "site .* symlink target is not a directory",
        )
