#!/usr/bin/python
# arch-tag: main entry point
# Copyright (C) 2003 John Goerzen
#               2008 Hubert Chathi
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 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 General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
#

import sys, os
sys.path.append('/usr/share/tla-buildpackage')
from vcs_support import util
from tbppy import versions, extcmd, tbpconfig
util.verbose = 1

if '-h' in sys.argv[1:] or '--help' in sys.argv[1:]:
    progname = os.path.basename(sys.argv[0])
    print """Usage: %s [debuild options]
       %s -h|--help|-v|--version
Build Debian packages from a tla/Arch archive

  -h, --help     display this help message and exit
  -v, --version  display version information and exit

All other options will be passed as-is to debuild.  See `debuild --help' for
more information.""" % (progname, progname)
    sys.exit(0)
if '-v' in sys.argv[1:] or '--version' in sys.argv[1:]:
    versions.print_tbp_version('tla-buildpackage')
    sys.exit(0)

debver, upstreamver, package, wcdir = tbpconfig.pkginit()

tgzname = "%s_%s.orig.tar.gz" % (package, upstreamver)
tgzpath = os.path.abspath(os.getcwd() + "/../%s" % tgzname)
origdirname = '%s-%s.orig' % (package, upstreamver)
origdir = os.path.abspath(os.getcwd() + "/../%s-%s.orig" % (package, upstreamver))
startdir = os.getcwd()

if versions.getdebianver(debver) and not os.path.isfile(tgzpath):
    if not os.path.isdir(origdir):
        # Need to build the orig dir so that the
        #system can generate the orig tgz
        os.chdir(wcdir)
        print "Building .orig from archive."
        extcmd.qrun('tla buildcfg upstream/%s/%s' % (package, upstreamver))
        os.chdir(startdir)
    os.chdir('..')
    extcmd.qrun('tla inventory -s "%s" | tar -cSpf - -T- | gzip -9 > "%s"' % \
                (origdirname, tgzname))

os.chdir(startdir)
print " *** Running build program"
util.safeexec("debuild",
              [r'-i(^|/)(\+\+pristine-trees|\{arch\}|\.arch-ids|\.arch-inventory)($|/)|(^|/),,',
               r'-I++pristine-trees', r'-I{arch}', r'-I.arch-ids',
               r'-I.arch-inventory', r'-I,,*'] + \
              sys.argv[1:])
