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

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()
