# 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 tarfile
from pathlib import Path

import mozfile
from mozpack.dmg import create_dmg

from mozbuild.bootstrap import bootstrap_toolchain
from mozbuild.repackaging.application_ini import get_application_ini_value


def repackage_dmg(infile, output, attribution_sentinel=None, compression=None):
    if not tarfile.is_tarfile(infile):
        raise Exception("Input file %s is not a valid tarfile." % infile)

    # Resolve required tools
    dmg_tool = bootstrap_toolchain("dmg/dmg")
    if not dmg_tool:
        raise Exception("DMG tool not found")
    hfs_tool = bootstrap_toolchain("dmg/hfsplus")
    if not hfs_tool:
        raise Exception("HFS tool not found")
    mkfshfs_tool = bootstrap_toolchain("hfsplus/newfs_hfs")
    if not mkfshfs_tool:
        raise Exception("MKFSHFS tool not found")

    with mozfile.TemporaryDirectory() as tmp:
        tmpdir = Path(tmp)
        mozfile.extract_tarball(infile, 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.
        symlink = tmpdir / " "
        if symlink.is_file():
            symlink.unlink()

        volume_name = get_application_ini_value(
            str(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(
            source_directory=tmpdir,
            output_dmg=Path(output),
            volume_name=volume_name,
            extra_files=[],
            dmg_tool=Path(dmg_tool),
            hfs_tool=Path(hfs_tool),
            mkfshfs_tool=Path(mkfshfs_tool),
            attribution_sentinel=attribution_sentinel,
            compression=compression,
        )
