#!/usr/bin/env python3
#
# makeupdates - Generate an updates.img containing changes since the last
#               tag.
#
# Copyright (C) 2023  Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# This should be eventually get shared across projects:
# https://issues.redhat.com/browse/INSTALLER-3755

import getopt
import os
import shutil
import sys


def addRpms(updates, add_rpms):
    for rpm in add_rpms:
        cmd = "cd %s && rpm2cpio %s | cpio -dium" % (updates, rpm)
        sys.stdout.write(cmd + "\n")
        os.system(cmd)


def createUpdatesImage(cwd, updates):
    os.chdir(updates)
    os.system("find . | cpio -c -o | gzip -9cv > %s/updates.img" % (cwd,))
    sys.stdout.write("updates.img ready\n")


def usage(cmd):
    sys.stdout.write("Usage: %s [OPTION]...\n" % (cmd,))
    sys.stdout.write("Options:\n")
    sys.stdout.write("    -h, --help       Display this help and exit.\n")
    sys.stdout.write("    -a, --add        Add contents of rpm to the update\n")


def main(argv):
    prog = os.path.basename(argv[0])
    cwd = os.getcwd()
    package_json = os.path.realpath(cwd + '/package.json')
    updates = cwd + '/updates'
    show_help, unknown = False, False
    opts = []
    add_rpms = []

    try:
        opts, _args = getopt.getopt(argv[1:], 'a', ['add=', 'help'])
    except getopt.GetoptError:
        show_help = True

    for o, a in opts:
        if o in ('-?', '--help'):
            show_help = True
        elif o in ('-a', '--add'):
            add_rpms.append(os.path.abspath(a))
        else:
            unknown = True

    if show_help:
        usage(prog)
        sys.exit(0)
    elif unknown:
        sys.stderr.write("%s: extra operand `%s'" % (prog, argv[1],))
        sys.stderr.write("Try `%s --help' for more information." % (prog,))
        sys.exit(1)

    if not os.path.isfile(package_json):
        sys.stderr.write("You must be at the top level of the repository source tree.\n")
        sys.exit(1)

    if not os.path.isdir(updates):
        os.makedirs(updates)

    if add_rpms:
        addRpms(updates, add_rpms)

    createUpdatesImage(cwd, updates)

    shutil.rmtree(updates)


if __name__ == "__main__":
    main(sys.argv)
