#!/usr/bin/env python3

import inspect
import json
import logging
import optparse
import os
import shutil
import sys
import tempfile
import unittest

localmodule = os.path.realpath(
    os.path.join(os.path.dirname(inspect.getfile(inspect.currentframe())), '..')
)
print('localmodule: ' + localmodule)
if localmodule not in sys.path:
    sys.path.insert(0, localmodule)

from fdroidserver import common, gpgsign
from pathlib import Path
from unittest.mock import MagicMock, patch


class GpgsignTest(unittest.TestCase):

    basedir = Path(__file__).resolve().parent

    def setUp(self):
        logging.basicConfig(level=logging.DEBUG)
        self.tempdir = tempfile.TemporaryDirectory()
        os.chdir(self.tempdir.name)
        self.repodir = Path('repo')
        self.repodir.mkdir()

        gpgsign.config = None
        config = common.read_config(common.options)
        config['verbose'] = True
        config['gpghome'] = str((self.basedir / 'gnupghome').resolve())
        config['gpgkey'] = '1DBA2E89'
        gpgsign.config = config

    def tearDown(self):
        self.tempdir.cleanup()

    @patch('sys.argv', ['fdroid gpgsign', '--verbose'])
    @patch('fdroidserver.gpgsign.FDroidPopen')
    def test_sign_index(self, FDroidPopen):
        """This skips running gpg because its hard to setup in a test env"""
        index_v1_json = 'repo/index-v1.json'
        shutil.copy(str(self.basedir / index_v1_json), 'repo')
        shutil.copy(str(self.basedir / 'SpeedoMeterApp.main_1.apk'), 'repo')

        def _side_effect(gpg):
            f = gpg[-1]
            sig = gpg[3]
            self.assertTrue(sig.startswith(f))
            open(sig, 'w').close()
            p = MagicMock()
            p.returncode = 0
            return p

        FDroidPopen.side_effect = _side_effect
        gpgsign.main()
        self.assertTrue(FDroidPopen.called)
        self.assertTrue((self.repodir / 'index-v1.json').exists())
        self.assertTrue((self.repodir / 'index-v1.json.asc').exists())
        self.assertTrue((self.repodir / 'SpeedoMeterApp.main_1.apk.asc').exists())
        self.assertFalse((self.repodir / 'index.jar.asc').exists())
        # smoke check status JSON
        with (self.repodir / 'status/gpgsign.json').open() as fp:
            data = json.load(fp)
        self.assertTrue('index-v1.json' in data['signed'])


if __name__ == "__main__":
    os.chdir(os.path.dirname(__file__))

    parser = optparse.OptionParser()
    parser.add_option(
        "-v",
        "--verbose",
        action="store_true",
        default=False,
        help="Spew out even more information than normal",
    )
    (common.options, args) = parser.parse_args(['--verbose'])

    newSuite = unittest.TestSuite()
    newSuite.addTest(unittest.makeSuite(GpgsignTest))
    unittest.main(failfast=False)
