#!/usr/bin/env python

# ***** BEGIN LICENSE BLOCK *****
# Source last modified: $Id: buildrpm.py,v 1.4.2.3 2004/09/29 18:44:23 rggammon Exp $
# 
# Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
# 
# The contents of this file, and the files included with this file,
# are subject to the current version of the RealNetworks Public
# Source License (the "RPSL") available at
# http://www.helixcommunity.org/content/rpsl unless you have licensed
# the file under the current version of the RealNetworks Community
# Source License (the "RCSL") available at
# http://www.helixcommunity.org/content/rcsl, in which case the RCSL
# will apply. You may also obtain the license terms directly from
# RealNetworks.  You may not use this file except in compliance with
# the RPSL or, if you have a valid RCSL with RealNetworks applicable
# to this file, the RCSL.  Please see the applicable RPSL or RCSL for
# the rights, obligations and limitations governing use of the
# contents of the file.
# 
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL") in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your version of
# this file only under the terms of the GPL, and not to allow others
# to use your version of this file under the terms of either the RPSL
# or RCSL, indicate your decision by deleting the provisions above
# and replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient may
# use your version of this file under the terms of any one of the
# RPSL, the RCSL or the GPL.
# 
# This file is part of the Helix DNA Technology. RealNetworks is the
# developer of the Original Code and owns the copyrights in the
# portions it created.
# 
# This file, and the files included with this file, is distributed
# and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
# KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
# ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
# ENJOYMENT OR NON-INFRINGEMENT.
# 
# Technology Compatibility Kit Test Suite(s) Location:
#    http://www.helixcommunity.org/content/tck
# 
# Contributor(s):
# 
# ***** END LICENSE BLOCK *****
######################################################################



import sys, getopt
import os, os.path



def usage():
    print "USAGE: buildrpm.py [options] src1 src2 src3..."
    print "-h, --help\tdisplay usage"
    print "-v, --verbose\tverbose mode"
    print "-n, --dryrun\tdry run mode (show cmds, don't execute)"
    print "-s, --spec\tpath to spec file (required)"
    print "-a, --arch\ttarget architecture (required, eg: i586, powerpc, etc...) "
    print "-b, --builddir\tbuild RPM in specified dir (optional, default = ./redhat)"
    print "-r, --release\tuse specified string for package version (optional)"
    print "-f, --verfile\tuse specified helix .ver file for package version (optional)"


def findrpm():
    # find either rpmbuild or rpm command (prefer rpmbuild)
    paths = os.getenv("PATH", "").split(os.pathsep)
    for p in paths:
        rpmcmd = os.path.join(p, "rpmbuild")
        if os.path.exists(rpmcmd):
            return rpmcmd
    for p in paths:
        rpmcmd = os.path.join(p, "rpm")
        if os.path.exists(rpmcmd):
            return rpmcmd
    print "no rpmbuild or rpm command found in PATH!"
    sys.exit(2)
    

def process(arch, spec, builddir, sources,
            version = None, verbose = 0, dryrun = 0):
    # get some important paths
    sources_dir = os.path.join(builddir, "SOURCES")
    specs_dir = os.path.join(builddir, "SPECS")
    spec_file = os.path.split(spec)[-1]
    dest_spec = os.path.join(specs_dir, spec_file)
    top_dir = os.path.join(os.getcwd(), builddir)
    cmds = []

    # remove old staging dir
    cmds.append("rm -rf %s" % builddir)

    # create staging dirs
    cmds.append("mkdir -p %s/{RPMS/{%s,noarch},SRPMS,SPECS,SOURCES,BUILD}" %
                (builddir, arch))

    # copy source files to staging area
    for src in sources:
        dest = os.path.join(sources_dir, os.path.split(src)[-1])
        cmds.append("cp %s %s" % (src, dest))

    # set stating area in spec
    cmds.append("echo \"%%define _topdir %s\" > %s" % (top_dir, dest_spec))

    
    # append remaining spec (update the version if provided)
    if version:
        cmds.append("sed -r -e 's/_REPLACE_VERSION_/%s/' %s >> %s" %
                    (version, spec, dest_spec))
    else:
        cmds.append("cat %s >> %s" % (spec, dest_spec))

    # cd to the specs dir and runthe rpmbuild/rpm command
    cmds.append("( cd %s ; %s -ba --target %s %s )" %
                (specs_dir, findrpm(), arch, spec_file))

    # display/run the commands
    for c in cmds:
        if verbose or dryrun:
            print c
        if not dryrun:
            os.system(c)

def get_helix_version(verfile):
    for line in file(verfile, "rt").readlines():
        stuff = line.split()
        if len(stuff) == 3 and stuff[1] == "TARVER_STRING_VERSION":
            return stuff[2][1:-1] # strip quotes
    assert("TARVER_STRING_VERSION not found in %s" % verfile)


def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ha:s:b:vnf:r:",
                                   [ "help", "arch", "spec", "builddir",
                                     "verbose", "dryrun",
                                     "verfile", "release" ])
                                     
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    verbose = 0
    dryrun = 0
    arch = None
    spec = None
    builddir = "redhat" # default
    version = None
    
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-a", "--arch"):
            arch = a
        elif o in ("-v", "--verbose"):
            verbose = 1
        elif o in ("-n", "--dryrun"):
            dryrun = 1
        elif o in ("-b", "--builddir"):
            builddir = a
        elif o in ("-s", "--spec"):
            spec = a
        elif o in ("-f", "--verfile"):
            version = get_helix_version(a)
        elif o in ("-r", "--release"):
            version = a

    if not arch:
        print "missing arch parameter"
        usage()
        sys.exit(1)

    if not spec:
        print "missing spec parameter"
        usage()
        sys.exit(1)

    if not args or not len(args):
        print "missing at least one src parameter"
        usage()
        sys.exit(1)

    for a in args:
        if not os.path.isfile(a):
            print "invalid source path \"%s\"" % a
            usage()
            sys.exit(3)

    if not os.path.isfile(spec):
        print "invalid spec path \"%s\"" % spec
        usage()
        sys.exit(3)

    process(arch, spec, builddir, args, version, verbose, dryrun)
    

if __name__ == "__main__":
    main()
