
# -*- coding: iso-8859-1 -*-

import os
import sys
import string
import popen2
import stat
import re
import time
from os import path
import getopt
import tempfile
import signal
import cmt

tempprefix = ''
tempfile1 = ''
tempfile2 = ''
tempcopydir = ''
tempcmtusercontext = ''
patch_requirements = ''

release = ''
cyclefile = ''
patch_dir = ''
minimal = False
pacman_only = False
platform = ''
platform_suffix = ''
override = False
do_source_kit = False
url = ''

pacman_base = ''
cache_dir = ''
kits_dir = ''

patch_requirements = ''

here = ''

cmt = cmt.CMT ()

def get_project (cmtpath):
    if cmtpath != '':
        rr = os.path.basename (cmtpath)
        pr = os.path.dirname (cmtpath)
        pr = os.path.basename (pr)
        return os.path.join (pr, rr)

def cleanup ():
    print 'Cleanup'
    cmt.removedirs (tempprefix)

def build_pacman (url, package, version, cmtpath, project_id, is_internal):
    #print url, package, version, cmtpath, project_id, is_internal

    source = '../kits'

    # External packages (those with export_paths) are split into two kits:
    # o The internal part, which follows the naming convention for internal packages
    # o The external part, which only refers to the package version (no mention of
    #   the project)

    # Naming cnvention:
    #  external packages : <package>-<version>-<platform>
    #  internal packages : <projectid>/<package>-<platform>

    if not is_internal:
        # first build the pacman file for the external stuff

        if native_version == None:
            #vv=`echo ${version} | sed -e 's#'^${package}-'##'`
            vv = ''
        else:
            vv = native_version
            download_filename="${package}-${vv}${platform_suffix}"
        download_filename = package + '-' + vv + platform_suffix

        pacman_filename = download_filename + '.pacman'

        print 'build_pacman> Create pacman file for external stuff ' + pacman_filename

        pacman_file_version = get_pacman_file_version (os.path.join (cache_dir, pacman_filename))

        #if test -f ${cache_dir}/${pacman_filename};  then
        # mv ${cache_dir}/${pacman_filename} ${cache_dir}/${pacman_filename}.bak
        # if test ! $? = 0; then
        #   print 'create_kit> failed to rename ' + cache_dir + '/' + pacman_filename + ' to ' + cache_dir + '/' + pacman_filename' + '.bak'
        # exit 1

    # write pacman file



    # end build_pacman

def usage ():
    print "Make a distribution kit for a CMT package"
    print "Usage: create_kit.sh [ <option> ... ] <pacman-cache>"
    print " where option can be:"
    print "  -r|--release <release-id>  : specify the release id"
    print "  -c|--cycles <cycles-file>  : specify the cycles file"
    print "  -P|--patches <patch-dir>   : specify a directory for patches "
    print "  -m|--minimal               : only store CMT files into the tar ball"
    print "  -O|--pacman_only           : do not generate the tar ball"
    print "  -p|--platform <platform>   : specify a platform suffix"
    print "  -o|--override              : override the existing tar balls"
    print "  -s|--source                : generate the source kit"
    print "Typical/example usage:"
    print "  cmt broadcast create_kit.sh -release 6.3.0 -cycles ${DEP}/cycles.txt /tmp "
    # end usage

#----------------------------------------------------
# Main
#----------------------------------------------------
def main ():

    print time.strftime ('%c')

    pwd = os.getcwd ()

    try:
        opts, args = getopt.getopt (sys.argv[1:] , 'r:c:P:mOp:osu:', ['release=', 'cycles=', 'patches=', 'minimal', 'pacman_only', 'platform=', 'override', 'source', 'url='])

    except getopt.GetoptError:
        # print help information and exit:
        usage()
        sys.exit(2)

    for o,a in opts:
        if o in ('-r', '--release'):
            release = a
        if o in ('-c', '--cycles'):
            cyclefile = a
        if o in ('-P', '--patches'):
            patch_dir = a
        if o in ('-m', '--minimal'):
            minimal = True
        if o in ('-O', '--pacman_only'):
            pacman_only = True
        if o in ('-p', '--platform'):
            platform = a
        if o in ('-o', '--override'):
            override = True
        if o in ('-s', '--source'):
            do_source_kit = True
        if o in ('-u', '--url'):
            url = a

    for a in args:
        pacman_base = os.path.normpath (a)
        cache_dir = os.path.join (pacman_base, os.path.normpath ('cache'))
        kits_dir = os.path.join (pacman_base, os.path.normpath ('kits'))

    #---------------
    # Prepare the target pacman cache 
    #

    if not os.path.isdir (cache_dir):
        print 'Creating ' + cache_dir
        os.makedirs (cache_dir)

    if not os.path.isdir (kits_dir):
        print 'Creating ' + kits_dir
        os.makedirs (kits_dir)

    here = os.path.dirname (sys.argv[0])
    if here == '':
        here = os.getcwd ()

    print 'here=' + here

    #---------------
    # Prepare temporary file management
    #

    #signal.signal (0, cleanup)
    #signal.signal (1, cleanup)
    #signal.signal (2, cleanup)
    #signal.signal (15, cleanup)

    tempprefix = 'CMT' + str(os.getpid ())
    print 'tempprefix=' + tempprefix

    tempfile1 = os.path.join (tempprefix, 't')
    tempfile2 = os.path.join (tempprefix, 'u')
    tempcopydir = os.path.join (tempprefix, 'c')
    tempcmtusercontext = os.path.join (tempprefix, 'd')

    cleanup ()

    os.makedirs (tempprefix)

    #---------------
    # Prepare the CMT and package context
    #

    h = cmt.do ('show pwd')
    root = os.path.dirname (h)

    cmtversion = cmt.do ('version')

    version = cmt.macro_value ('version')
    if version == 'v*':
        version = 'v1'

    print 'cmtversion=' + cmtversion
    print 'version' + version

    package = cmt.macro_value ('package')
    if package != '':
        package = os.path.normpath (package)
        
    cmtpath = cmt.macro_value (package + '_cmtpath')
    if cmtpath != '':
        cmtpath = os.path.normpath (cmtpath)

    offset = cmt.macro_value (package + '_offset')
    if offset != '':
        offset = os.path.normpath (offset)

    print 'package=' + package
    print 'cmtpath=' + cmtpath
    print 'offset=' + offset

    project = cmt.macro_value (package + '_project')
    print 'package_project=' + project

    release = cmt.macro_value (package + '_project_release')
    print 'package_project_release=' + release
    
    print 'CMTPATH=' + cmt.macro_value ('CMTPATH')

    if cmtpath == '':
        cmtpath = os.path.normpath (cmt.macro_value (package + '_root'))
        cmtpath = os.path.dirname (cmtpath)
        cmtpath = os.path.dirname (cmtpath)

    print '# Working on ' + package + ' ' + version + ' ' + offset + ' in ' + cmtpath + ' project ' + project + ' ' + release

    cleanup ()
    sys.exit (0)

    #---------------
    # Prepare the patch structure
    #

    if options.patch_dir != None:
        if os.path.isdir (os.path.join (options.patch_dir, project_id)):
            print 'create_kit> ' + options.patch_dir + '/' + project_id
            os.makedirs (tempcmtusercontext)
            os.putenv ('CMTUSERCONTEXT', tempcmtusercontext)
            patch_requirements = os.path.join (tempcmtusercontext, os.path.normpath ('requirements'))
            f = open (patch_requirements, 'w+')
            
    #---------------
    # Prepare the detection of external packages
    #

    native_version = cmt.macro_value (package + '_native_version')
    export_paths = cmt.macro_value (package + '_export_paths')

    is_internal = export_paths == None

    if options.do_source_kit:
        is_internal = True
            
    #---------------
    # Prepare the temporary copies
    #

    os.makedirs (tempcopydir)
    copycmd = 'ln -s'

    #---------------
    # Generate the pacman file
    #

    build_pacman (options.url, package, version, cmtpath, project_id, is_internal)

    #---------------
    # 
    #

    cleanup ()

if __name__ == '__main__':
    main()

