#!/usr/bin/python3

# Repack a click package by using lowlevel tools so as not to change anything
# in the package (ie, don't use 'click build .' to avoid updating DEBIAN/, etc)

import sys
import os

from clickreviews import common
from debian.deb822 import Deb822
import glob
import shutil
import tempfile


def repack_click(unpack_dir, click_package):
    '''Repack the click package'''
    if not os.path.isdir(unpack_dir):
        common.error("'%s' does not exist" % unpack_dir)
    if os.path.exists(click_package):
        common.error("'%s' exists" % click_package)

    control_fn = os.path.join(unpack_dir, "DEBIAN/control")
    if not os.path.exists(control_fn):
        common.error("Could not find '%s'" % control_fn)
    fh = common.open_file_read(control_fn)
    tmp = list(Deb822.iter_paragraphs(fh.readlines()))
    fh.close()
    if len(tmp) != 1:
        common.error("malformed control file: too many paragraphs")
    control = tmp[0]

    click_fn = "%s_%s_%s.click" % (control['Package'],
                                   control['Version'],
                                   control['Architecture'])
    if os.path.basename(click_package) != click_fn:
        common.warn("'%s' should be '%s'" % (click_package, click_fn))

    tmpdir = tempfile.mkdtemp(prefix='clickreview-')
    curdir = os.getcwd()
    os.chdir(tmpdir)
    (rc, out) = common.cmd(['dpkg-deb', '-b', '--nocheck', '-Zgzip',
                               os.path.abspath(unpack_dir),
                               os.path.join(tmpdir, click_fn)])
    os.chdir(curdir)
    if rc != 0:
        common.recursive_rm(tmpdir)
        common.error("dpkg-deb -b failed with '%d':\n%s" % (rc, out))

    debfile = glob.glob("%s/*.click" % tmpdir)[0]
    shutil.move(debfile, os.path.abspath(click_package))
    common.recursive_rm(tmpdir)


if __name__ == '__main__':
    if len(sys.argv) != 3:
        common.error("%s <unpacked dir> <clickpkg>" %
                        os.path.basename(sys.argv[0]))

    dir = sys.argv[1]
    pkg = sys.argv[2]

    repack_click(dir, pkg)
    print("Successfully repacked to '%s'" % pkg)
