# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

import errno
import os
import tempfile
import tarfile
import shutil
import mozpack.path as mozpath
from mozpack.dmg import create_dmg
from application_ini import get_application_ini_value

def repackage_dmg(infile, output):

    if not tarfile.is_tarfile(infile):
        raise Exception("Input file %s is not a valid tarfile." % infile)

    tmpdir = tempfile.mkdtemp()
    try:
        with tarfile.open(infile) as tar:
            tar.extractall(path=tmpdir)

        # Remove the /Applications symlink. If we don't, an rsync command in
        # create_dmg() will break, and create_dmg() re-creates the symlink anyway.
        try:
            os.remove(mozpath.join(tmpdir, ' '))
        except OSError as e:
            if e.errno != errno.ENOENT:
                raise

        volume_name = get_application_ini_value(tmpdir, 'App', 'CodeName',
                                                fallback='Name')

        # The extra_files argument is empty [] because they are already a part
        # of the original dmg produced by the build, and they remain in the
        # tarball generated by the signing task.
        create_dmg(tmpdir, output, volume_name, [])

    finally:
        shutil.rmtree(tmpdir)
