#!/usr/bin/python

# This is part of the Mer git-packaging suite
# It takes a spec file and applies any patches found to the git tree

import sys
import re
import subprocess


spec_f = open(sys.argv[1])

patch_definition = re.compile(r"^Patch(\d{1,4}):\s*(\S+)\s*$")
patch_application = re.compile(r"^%patch(\d{1,4})\s+.*$")
patches = {}

for line in spec_f:
    m = patch_definition.search(line)
    if m:
        num, patch = m.group(1,2)
        patches[num] = patch
        print "Found patch %(num)s as %(patch)s" % locals()

    m = patch_application.search(line)
    if m:
        num = m.group(1)
        name = patches[num]
        print "Applying patch %s : %s" % (num, name)
        subprocess.call(["/usr/bin/git", "apply", "../%s" % name ])

        if name.endswith(".patch"):
            name = name[:-6]
        subprocess.call(["/usr/bin/git", "commit", "-a", "-m", name ])
                         
