import getpass
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from cam import main


class MainTest(unittest.TestCase):

    def setUp(self):
        self.tmpdir = tempfile.mkdtemp()
        self.cfgfile = os.path.join(self.tmpdir, 'test.conf')
        with open(self.cfgfile, 'w') as fd:
            fd.write("""
[ca]
cn = Test Ca
org = Test
country = IE
email = ca@test.org
bits = 1024

[web]
cn = www.test.org
""")

        def _fake_getpass(prompt):
            return 'testpass'
        getpass.getpass = _fake_getpass

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

    def _run(self, *args):
        sys.argv = ['cam', '--config=%s' % self.cfgfile] + list(args)
        try:
            return main.main()
        except SystemExit, e:
            return e.code

    def test_init_and_sanity_check(self):
        self.assertEquals(None, self._run('init'))
        self.assertEquals(None, self._run('gen', 'web'))

        ca_file = os.path.join(self.tmpdir, 'public/ca.pem')
        crt_file = os.path.join(self.tmpdir, 'public/certs/web.pem')
        self.assertTrue(os.path.exists(ca_file))
        self.assertTrue(os.path.exists(crt_file))

        subprocess.call(['openssl', 'x509', '-in', ca_file,
                         '-noout', '-text'])
        subprocess.call(['openssl', 'x509', '-in', crt_file,
                         '-noout', '-text'])

        pipe = subprocess.Popen(
            ['openssl', 'verify', '-CAfile', ca_file, '-verbose', crt_file],
            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        output = pipe.communicate()[0]
        result = pipe.returncode
        self.assertEquals(0, result)

        print output
        self.assertTrue('error ' not in output)
             
