#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2018 Simon McVittie <smcv@debian.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# You can find the GPL license text on a Debian system under
# /usr/share/common-licenses/GPL-2.

import subprocess

from . import (SimpleUnpackable)


class InnoSetup(SimpleUnpackable):
    """Object representing an InnoSetup installer.
    """

    def __init__(self, path, verbose=False, language=None):
        """Constructor.

        path may be a string or bytes object.
        """
        self.path = path
        self.verbose = verbose
        self.language = language

    def __enter__(self):
        return self

    def __exit__(self, _et, _ev, _tb):
        pass

    def extractall(
        self,
        path,
        members=None,
        *,
        capture_output=False,
        rename_collisions=False
    ):
        argv = [
            'innoextract',
            '-T', 'local',
            '-d', path,
            self.path,
        ]

        if members is not None:
            for member in members:
                argv.append('-I')
                argv.append(member)

        if rename_collisions:
            argv.append('--collisions=rename')

        if not self.verbose and not capture_output:
            argv.append('--silent')
            argv.append('--progress')

        if self.language is not None:
            argv.append('--language')
            argv.append(self.language)

        if capture_output:
            return subprocess.check_output(
                argv,
                stderr=subprocess.DEVNULL,
                universal_newlines=True,
            )
        else:
            subprocess.check_call(argv)

    def printdir(self):
        subprocess.check_call([
            'innoextract',
            '--default-language', (self.language or 'english'),
            '-T', 'local',
            '--list',
            self.path,
        ])

    @property
    def format(self):
        return 'innoextract'


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--output', '-o', help='extract to OUTPUT', default=None)
    parser.add_argument(
        '--verbose', '-v', help='Be verbose', action='store_true')
    parser.add_argument('setup_exe')
    args = parser.parse_args()

    setup = InnoSetup(args.setup_exe, verbose=args.verbose)

    if args.output:
        setup.extractall(args.output)
    else:
        setup.printdir()
