#!/usr/bin/python

import os, sys, time, re
from optparse import OptionParser
from glob import glob
import tempfile

import geet

op = OptionParser(usage="Usage: $prog [options] [rpmbuild_or_hasher_options]")
op.set_usage("""
    $prog [--hsh] [--ref <refspec>] [--commit | --no-commit] [-- <hasher or rpmbuild options>]
        """)
op.add_option("--hsh", help="Build rpm in hasher", action="store_true")
op.add_option("--ref", help="Git refspec to build")
op.add_option("--commit", help="Create temporary commit from working tree. Ignored if --ref option is used.", action="store_true")
op.add_option("--no-commit", help="Don't create temporary commit from working tree", action="store_false", dest="commit")
op.disable_interspersed_args()
(params, args) = op.parse_args()
if params.hsh is None:
    if sys.argv[0][-3:] == 'hsh':
        params.hsh = True
    else:
        params.hsh = False
if params.commit is None:
    params.commit = True
if params.ref:
    params.commit = False

wd = os.getcwd()
while not os.path.isdir(wd + "/.gear") and not os.path.exists(wd + '/.gear-rules'):
    #print wd, not os.path.isdir(wd + "/.gear") or not os.path.exists(wd + '/.gear-rules')
    wd = os.path.dirname(wd)
    if wd == '/':
        sys.stderr.write("Error: gear repository not found\n")
        exit(1)

git = geet.git.Git(tempfile.mkdtemp('','geet-build-tmp') + '/git')
if params.ref:
    git.fetch(os.path.abspath('.'), params.ref, '--depth=1')
    git.checkout('FETCH_HEAD', '-b build')
else:
    if params.commit:
        wgit = geet.git.Git(wd)
        sha = wgit.rev_parse('--verify HEAD')[0][:-1]
        try:
            wgit.commit('-a -m "Temporary commit"')
        except:
            pass
        git.fetch(os.path.abspath(wd), '', '--depth=1')
        git.checkout('FETCH_HEAD', '-b build')
        wgit.reset(['--soft', sha])
    else:
        git.fetch(os.path.abspath(wd), '', '--depth=1')
        git.checkout('FETCH_HEAD', '-b build')

os.chdir(git.get_path())
spec = glob('*.spec')[0]
rel_suffix = time.strftime("dbg%Y.%m.%d.%H.%M")
geet.utils.write_release(spec, rel_suffix, "Debug rpm")
if params.hsh:
    geet.utils.system('gear --commit --hasher -- hsh %s' % ' '.join(args))
else:
    geet.utils.system('gear --commit --rpmbuild -- rpmbuild %s' % ' '.join(args))
geet.utils.rmdir(git.get_path())

