#!/usr/local/munki/munki-python
# encoding: utf-8
#
# Copyright 2009-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.
"""
makecatalogs

Created by Greg Neagle on 2009-03-30.

Recursively scans a directory, looking for installer item info files.
Builds a repo catalog from these files.

Assumes a pkgsinfo directory under repopath.
User calling this needs to be able to write to repo/catalogs.

"""
from __future__ import absolute_import, print_function

import optparse
import sys

from munkilib.admin import makecatalogslib
from munkilib.cliutils import pref, path2url
from munkilib.cliutils import get_version
from munkilib import munkirepo
from munkilib.wrappers import unicode_or_str

# define a unicode function for Python 3
try:
    # Python 2
    _ = unicode # pylint: disable=unicode-builtin
except NameError:
    # Python 3
    unicode = str


def main():
    '''Main'''
    usage = "usage: %prog [options] [/path/to/repo_root]"
    parser = optparse.OptionParser(usage=usage)
    parser.add_option('--version', '-V', action='store_true',
                      help='Print the version of the munki tools and exit.')
    parser.add_option('--force', '-f', action='store_true', dest='force',
                      help='Disable sanity checks.')
    parser.add_option('--skip-pkg-check', '-s', action='store_true',
                      dest='skip_payload_check',
                      help='Skip checking of pkg existence. Useful '
                           'when pkgs aren\'t on the same server '
                           'as pkginfo, catalogs and manifests.')
    parser.add_option('--repo_url', '--repo-url',
                      help='Optional repo URL that takes precedence '
                           'over the default repo_url specified via '
                           '--configure.')
    parser.add_option('--plugin',
                      help='Specify a custom plugin to connect to repo.')
    parser.set_defaults(force=False, skip_payload_check=False)
    options, arguments = parser.parse_args()

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

    # backwards compatibility
    if not options.repo_url and not options.plugin:
        if arguments:
            options.repo_url = path2url(arguments[0])
        elif pref('repo_url'):
            options.repo_url = pref('repo_url')
            options.plugin = pref('plugin')
        elif pref('repo_path'):
            options.repo_url = path2url(pref('repo_path'))

    if not options.repo_url:
        parser.print_usage()
        exit(-1)

    # Connect to the repo
    try:
        repo = munkirepo.connect(options.repo_url, options.plugin)
    except munkirepo.RepoError as err:
        print(u'Could not connect to munki repo: %s' % unicode_or_str(err),
              file=sys.stderr)
        exit(-1)

    # Make the catalogs
    try:
        errors = repo.makecatalogs(options, output_fn=print)
    except AttributeError:
        errors = makecatalogslib.makecatalogs(repo, options, output_fn=print)

    if errors:
        # group all errors at the end for better visibility
        print()
        for error in errors:
            print(error, file=sys.stderr)
        exit(-1)


if __name__ == '__main__':
    main()
