#!/usr/local/munki/munki-python
# encoding: utf-8
#
# Copyright 2008-2024 Greg Neagle.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
makepkginfo

Created by Greg Neagle on 2008-11-25.
Creates a managed install pkg info plist given an Installer item:
a .pkg, a .mpkg, or a .dmg containing a .pkg or .mpkg
at the root of the mounted disk image.

You may also pass additional items that are installed by the package. These
are added to the 'installs' key of the catalog item plist and are used when
processing the catalog to check if the package needs to be installed or
reinstalled.

The generated plist is printed to STDOUT.

Usage: makepkginfo /path/to/package_or_dmg [-f /path/to/item/it/installs ...]
"""
from __future__ import absolute_import, print_function

# standard libs
import optparse
import sys

# our libs
from munkilib import info
from munkilib import osutils
from munkilib import FoundationPlist
from munkilib.admin import pkginfolib


def has_valid_install_criteria(pkginfo):
    """
    Inspects compiled catalog info dictionary for valid install criteria.
    Returns boolean.
    """
    return (pkginfo.get('installs')
            or pkginfo.get('receipts')
            or pkginfo.get('installcheck_script')
            or pkginfo.get('installer_type') == 'profile'
            or pkginfo.get('installer_type') == 'apple_update_metadata'
            or pkginfo.get('installer_type') == 'startosinstall')


def main():
    '''Main routine'''
    usage = """usage: %prog [options] [/path/to/installeritem]
       %prog --help for more information."""
    parser = optparse.OptionParser(usage=usage)
    parser.add_option(
        '--version', '-V',
        action='store_true',
        help='Print the version of the munki tools and exit.'
        )
    # add all our option groups
    pkginfolib.add_option_groups(parser)

    #sys.argv = [unicode(item, 'utf-8') for item in sys.argv]
    options, arguments = parser.parse_args()

    if options.version:
        print(info.get_version())
        exit(0)

    if (not arguments and
            not options.file and
            not options.nopkg and
            not options.installer_environment and
            not options.installcheck_script and
            not options.uninstallcheck_script and
            not options.preinstall_script and
            not options.postinstall_script and
            not options.preuninstall_script and
            not options.postuninstall_script and
            not options.uninstall_script and
            not options.apple_update):
        parser.print_usage()
        exit(-1)

    if (options.minimum_os_version and
            not options.minimum_os_version[0].isdigit()):
        print('Minimum OS Version must start with a number, e.g. 10.7.2.',
              file=sys.stderr)
        exit(-1)

    if len(arguments) > 1:
        print('Can process only one installer item at a time.', file=sys.stderr)
        print('Ignoring additional installer items:', file=sys.stderr)
        print('\t', '\n\t'.join(arguments[1:]), file=sys.stderr)

    os_version = osutils.getOsVersion(
        only_major_minor=False, as_tuple=True)
    if options.installer_choices_xml:
        if os_version < (10, 6, 6):
            options.installer_choices_xml = False

    if arguments:
        installeritem = arguments[0].rstrip("/")
    else:
        installeritem = None
    try:
        pkginfo = pkginfolib.makepkginfo(installeritem, options)
    except pkginfolib.PkgInfoGenerationError as err:
        print(err, file=sys.stderr)
        exit(-1)

    if (len(arguments) == 1 and
            not has_valid_install_criteria(pkginfo)):
        item = pkginfo['name']
        msg = (
            "WARNING: pkginfo for '%s' contains no installation check info!\n"
            "    No useful receipts were detected, and no 'installs' "
            "items were provided.\n"
            "    If you do not add an 'installs' item or "
            "an installcheck_script,\n"
            "    Munki will have no way to determine the item's installation "
            "state.\n"
            "    This can result in repeated installation attempts or failure "
            "to attempt\n"
            "    installation at all.")
        print(msg % item, file=sys.stderr)

    # and now, what we've all been waiting for...
    print(FoundationPlist.writePlistToString(pkginfo).decode('UTF-8'))


if __name__ == '__main__':
    main()
