#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2008 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# 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.
""" Provides a generic wrapper of the pbuilder debian utility """
__docformat__ = "restructuredtext en"

import optparse
import sys
import os
import os.path as osp
import shutil
from subprocess import Popen, PIPE
try:
    from subprocess import call, check_call
except ImportError:
    from logilab.common.compat import call, check_call

from logilab.devtools.lgp import CONFIG_FILE

def test_arch(target_arch):
    """ Return True if the arch of localhost is target_arch """
    cmd = ['dpkg-architecture', '-e%s' % target_arch]
    return 0 == call(cmd)

def build(source_control, distribution, arch, resultdir, basetgz,
          binary_arch=False, orig_tarball=None):

    srcdir = osp.dirname(source_control)

    substitutions = {'distrib': distribution,
                     'arch': arch,}
    resultdir %= substitutions
    basetgz   %= substitutions

    if not osp.isdir(resultdir):
        os.makedirs(resultdir)

    cmd = ['sudo', 'DIST=%s' % distribution, 'pbuilder', '--build',
           '--configfile', CONFIG_FILE, '--buildresult', srcdir, source_control]

    if binary_arch:
        cmd.insert(-2, '--binary-arch')

    result = check_call(cmd)
    for filename in os.listdir(srcdir): # FIXME double-check condition below
        if osp.isfile(filename):
            shutil.copy(osp.join(srcdir, filename), resultdir)
    return result


def run():
    parser = optparse.OptionParser()
    parser.add_option('-d', '--distribution',
                      default="sid", help="target distribution")
    parser.add_option('-a', '--arch',
                      default=None, help="target architecture (defaults to local host's arch)")
    parser.add_option('-b', '--binary-arch',
                      default=False, action='store_true',
                      help="only build arch-specific targets instead of all targets")
    parser.add_option('-o', '--orig',
                      help='path to orig.tar.gz tarball (used when debian revision is > 1)')
    parser.add_option('-r', '--result',
                      help = 'directory where the build results is stored. '
                             'The strings "%(distrib)s" and "%(arch)s" will be substituted '
                             '[default: %default]',
                      default = '/opt/buildd/%(distrib)s')
    parser.add_option('--basetgz',
                      help='path to the base tar.gz archive. '
                           'The strings "%(distrib)s" and "%(arch)s" will be substituted '
                           '[default: %default]',
                      default = '/opt/buildd/%(distrib)s.tgz')
    usage = '%prog [options] <dsc file>'

    options, arguments = parser.parse_args()

    if not(options.arch is None or test_arch(options.arch)):
        parser.error('Cross building not supported for now')

    if len(arguments) != 1:
        parser.error('Missing argument : debian source control file (package_version.dsc)')
    dscfile = arguments[-1]
    if not osp.isfile(dscfile):
        parser.error('Cannot find %s' % dscfile)

    return build(arguments[-1],
                 options.distribution,
                 options.arch,
                 options.result,
                 options.basetgz,
                 options.binary_arch,
                 options.orig
                )

if __name__ == '__main__':
    sys.exit(run())
