#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2016-2018 Simon McVittie <smcv@debian.org>
# SPDX-License-Identifier: GPL-2.0-or-later

import os
import subprocess
import sys
import unittest
from tempfile import (TemporaryDirectory)

if 'GDP_UNINSTALLED' not in os.environ:
    sys.path.insert(0, '/usr/share/game-data-packager')
    sys.path.insert(0, '/usr/share/games/game-data-packager')

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from game_data_packager.version import (FORMAT, GAME_PACKAGE_VERSION)

class IntegrationTestCase(unittest.TestCase):
    def setUp(self):
        pass

    def test_scummvm(self):
        with TemporaryDirectory(prefix='gdptest.') as tmp:
            os.mkdir(os.path.join(tmp, 'in'))
            os.mkdir(os.path.join(tmp, 'out'))

            K = b'\0' * 1024

            with open(os.path.join(tmp, 'in', '1K.0'), 'wb') as writer:
                writer.write(K)

            with open(os.path.join(tmp, 'in', '4K.0'), 'wb') as writer:
                for i in range(4):
                    writer.write(K)

            with open(os.path.join(tmp, 'in', '1M.0'), 'wb') as writer:
                for i in range(1024):
                    writer.write(K)

            with open(os.path.join(tmp, 'in', 'manual.pdf'), 'wb') as writer:
                writer.write(b'this is not a PDF\n')

            with open(os.path.join(tmp, 'in', 'booklet.pdf'), 'wb') as writer:
                writer.write(b'this is not a PDF either\n')

            if 'GDP_BUILDDIR' in os.environ:
                builddir = os.environ['GDP_BUILDDIR']
            else:
                builddir = os.path.join(os.getcwd(), 'out')

            if not os.path.exists(os.path.join(builddir, 'meson-info')):
                subprocess.check_call([
                    os.environ.get('MAKE', 'make'),
                    'out/tests/changelog.gz',
                    'out/tests/copyright',
                    'out/tests/vfs.zip',
                ])

            env = os.environ.copy()
            env['GDP_PKGDATADIR'] = os.path.join(builddir, 'tests')

            if 'GDP_UNINSTALLED' in os.environ:
                argv = [
                    os.path.join(
                        os.environ.get('GDP_BUILDDIR', 'out'),
                        'run-gdp-uninstalled',
                    )
                ]
            else:
                argv = ['game-data-packager']

            argv = argv + [
                '-d', os.path.join(tmp, 'out'),
                '--no-compress',
                'scummvm',
                '--no-download',
                '--no-search',
                os.path.join(tmp, 'in'),
            ]

            # stdout=2 is effectively 2>&1
            subprocess.check_call(argv, env=env, stdout=2)

            if FORMAT == 'deb':
                import debian.deb822

                doc_deb = os.path.join(
                    tmp, 'out', 'larry-doc_%s_all.deb' % GAME_PACKAGE_VERSION)
                vga_deb = os.path.join(
                    tmp, 'out',
                    'larry6-data_1.000.000+%s_all.deb' % GAME_PACKAGE_VERSION)
                svga_deb = os.path.join(
                    tmp, 'out',
                    (
                        'larry6-svga-data_1.000.000+%s_all.deb'
                        % GAME_PACKAGE_VERSION
                    ))

                self.assertTrue(os.path.isfile(doc_deb))
                self.assertTrue(os.path.isfile(vga_deb))
                self.assertTrue(os.path.isfile(svga_deb))

                blob = subprocess.check_output(
                    ['dpkg-deb', '-f', doc_deb],
                )
                meta = debian.deb822.Deb822(blob)

                self.assertEqual(meta.get('Package'), 'larry-doc')
                self.assertEqual(meta.get('Version'), GAME_PACKAGE_VERSION)
                self.assertEqual(meta.get('Priority'), 'optional')
                self.assertEqual(meta.get('Section'), 'local/doc')
                self.assertEqual(meta.get('Architecture'), 'all')
                self.assertEqual(meta.get('Multi-Arch'), 'foreign')
                self.assertEqual(
                    meta.get('Depends'),
                    'larry1-data | larry2-data | larry3-data | larry5-data | '
                    'larry6-data | larry6-svga-data')
                self.assertEqual(meta.get('Recommends'), None)
                self.assertIn(
                    'Genre: Adventure',
                    meta.get('Description'))
                self.assertIn(
                    'Documentation: A ScummVM test vaguely resembling '
                    'Leisure Suit Larry 6',
                    meta.get('Description'))
                self.assertIn(
                    'Published by: nobody',
                    meta.get('Description'))

                blob = subprocess.check_output(
                    ['dpkg-deb', '-f', vga_deb],
                )
                meta = debian.deb822.Deb822(blob)

                self.assertEqual(meta.get('Package'), 'larry6-data')
                self.assertEqual(
                    meta.get('Version'), '1.000.000+' + GAME_PACKAGE_VERSION)
                self.assertEqual(meta.get('Priority'), 'optional')
                self.assertEqual(meta.get('Section'), 'local/games')
                self.assertEqual(meta.get('Architecture'), 'all')
                self.assertEqual(meta.get('Multi-Arch'), 'foreign')
                self.assertEqual(meta.get('Depends'), None)
                self.assertEqual(meta.get('Recommends'), 'scummvm')
                self.assertIn(
                    'Genre: Adventure',
                    meta.get('Description'))
                self.assertIn(
                    'Game: A ScummVM test vaguely resembling '
                    'Leisure Suit Larry 6',
                    meta.get('Description'))
                self.assertIn(
                    'Published by: nobody',
                    meta.get('Description'))

                blob = subprocess.check_output(
                    ['dpkg-deb', '-f', svga_deb],
                )
                meta = debian.deb822.Deb822(blob)

                self.assertEqual(meta.get('Package'), 'larry6-svga-data')
                self.assertEqual(
                    meta.get('Version'), '1.000.000+' + GAME_PACKAGE_VERSION)
                self.assertEqual(meta.get('Priority'), 'optional')
                self.assertEqual(meta.get('Section'), 'local/games')
                self.assertEqual(meta.get('Architecture'), 'all')
                self.assertEqual(meta.get('Multi-Arch'), 'foreign')
                self.assertEqual(meta.get('Depends'), None)
                self.assertEqual(meta.get('Recommends'), 'scummvm')
                self.assertEqual(meta.get('Breaks'), 'scummvm (<< 2.0.0~)')
                self.assertIn(
                    'Genre: Adventure',
                    meta.get('Description'))
                self.assertIn(
                    'Game: A ScummVM test vaguely resembling '
                    'Leisure Suit Larry 6',
                    meta.get('Description'))
                self.assertIn(
                    'Published by: nobody',
                    meta.get('Description'))

                contents = subprocess.check_output(
                    ['dpkg-deb', '--contents', doc_deb],
                    universal_newlines=True,
                )
                self.assertIn(
                    './usr/share/doc/larry-doc/\n', contents)
                self.assertIn(
                    './usr/share/doc/larry-doc/booklet.pdf\n', contents)
                self.assertIn(
                    './usr/share/doc/larry-doc/changelog.gz\n', contents)
                self.assertIn(
                    './usr/share/doc/larry-doc/copyright\n', contents)
                self.assertNotIn(
                    './usr/share/applications/\n', contents)

                contents = subprocess.check_output(
                    ['dpkg-deb', '--contents', vga_deb],
                    universal_newlines=True,
                )
                self.assertIn(
                    './usr/share/applications/larry6-data.desktop\n', contents)
                self.assertIn(
                    './usr/share/doc/larry6-data/changelog.gz\n', contents)
                self.assertIn(
                    './usr/share/doc/larry6-data/copyright\n', contents)
                self.assertIn(
                    './usr/share/doc/larry6-data/manual.pdf\n', contents)
                self.assertIn(
                    './usr/share/games/larry6/1K.0\n', contents)
                self.assertIn(
                    './usr/share/games/larry6/4K.0\n', contents)
                self.assertNotIn(
                    './usr/share/games/larry6/1M.0\n', contents)

                contents = subprocess.check_output(
                    ['dpkg-deb', '--contents', svga_deb],
                    universal_newlines=True,
                )
                self.assertIn(
                    './usr/share/applications/larry6-svga-data.desktop\n',
                    contents)
                self.assertIn(
                    './usr/share/doc/larry6-svga-data/changelog.gz\n',
                    contents)
                self.assertIn(
                    './usr/share/doc/larry6-svga-data/copyright\n', contents)
                self.assertIn(
                    './usr/share/doc/larry6-svga-data/manual.pdf\n', contents)
                self.assertIn(
                    './usr/share/games/larry6-svga/1K.0\n', contents)
                self.assertNotIn(
                    './usr/share/games/larry6-svga/4K.0\n', contents)
                self.assertIn(
                    './usr/share/games/larry6-svga/1M.0\n', contents)

            if 'GDP_TEST_ALL_FORMATS' in os.environ:
                for f in 'arch deb rpm'.split():
                    subprocess.check_call(
                        argv + ['--target-format', f],
                        env=env,
                    )

    def tearDown(self):
        pass

if __name__ == '__main__':
    from gdp_test_common import main
    main()
