#!/usr/bin/env python
################################################################################################
# @(#) $Id$
#
#    ALMA - Atacama Large Millimiter Array
#    (c) Associated Universities, Inc. Washington DC, USA, 2001
#    (c) European Southern Observatory, 2002
#    Copyright by ESO (in the framework of the ALMA collaboration)
#    and Cosylab 2002, All rights reserved
#
#    This library is free software; you can redistribute it and/or
#    modify it under the terms of the GNU Lesser General Public
#    License as published by the Free Software Foundation; either
#    version 2.1 of the License, or (at your option) any later version.
#
#    This library 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
#    Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public
#    License along with this library; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
################################################################################################
'''
This script is designed to rebuild RTOS avoiding putting rtaos.src.tar.gz into $ACSROOT
'''
################################################################################################

# Import system modules
import os
import getpass
import sys
import string
import time

##############################################################################      
def timeStamp():
    # Get a current Time Stamp - Format 
    item = time.localtime()
    data = "%02d.%02d.%d-%02d.%02d.%02d" % (item[2], item[1], item[0], item[3],item[4],item[5])
    return(data)

##############################################################################      
          
def checkConf(localDir):
    # Needed to test if you are running the right environment
    if  not os.environ.has_key('ACSROOT'):
        print "$ACSROOT is not defined, you dont' have the right environemnt\n"
        sys.exit(1)
    
    if not os.environ.has_key('LINUX_HOME'):
        print "$LINUX_HOME is not defined, you cannot install RTAI\n"
        sys.exit(1)
        
    if not os.environ.has_key('RTAI_HOME'):
        print "$RTAI_HOME is not defined, you cannot install RTAI\n"
        sys.exit(1)
        
    if os.getuid() == 0 :
        print "You shouldn't be root to run this script"
        sys.exit(1)
    
    if not os.access(localDir, os.R_OK) and not os.path.isdir(localDIr):
        print "Temporary directory ", localDir, " is not existing or is not readable\n"
        print "Please check directory or modify line\n"
        print " 'localDir =' in the script accordingly"
        sys.exit(1)
##############################################################################      
     
def extractSource(option, param, localDir, currentDir, now):
    
    
    CVS = '/usr/bin/cvs co '
    TAR = '/bin/tar xzvf '
    RTOSCVS = 'ACS/NO-LGPL/rtos'
    
    logFile  = currentDir + '/RTOSextract.log'
    if os.path.isdir(logFile) or os.path.isfile(logFile):
        newFileName = logFile + '-' + now
        print 'The file ' + logFile + ' is already there: Renaming it to ' + newFileName
        os.rename(logFile, newFileName)
    if option == 't':
        # Check if $CVSROT is defined
        if not os.environ.has_key('CVSROOT'):
            print "$CVSROOT is not defined, you cannot install use cvs\n"      
            sys.exit(1)
        temporaryDir = localDir + '/ ' + RTOSCVS
        extractCommand = CVS + '-r ' + param + '  ' + RTOSCVS + ' 2>&1 >& ' + logFile
    else:
        # Required tar file
        temporaryDir = localDir + '/rtos'
        extractCommand = TAR + param  + ' 2>&1 >& ' + logFile
    
    # Remove the directory if present
    if os.path.isdir(temporaryDir):
        newdirName = temporaryDir + '-' + now
        print 'The directory ' + temporaryDir + ' is already there: Renaming it to ' + newdirName
        os.rename(temporaryDir, temporaryDir)
    
    log = open(logFile, "a+")
    log.write("===================== Extract Command ==========================================\n")
    log.write(extractCommand + "\n")
    log.write("================================================================================\n")
    log.close()    
    
    os.chdir(localDir)
    #print "extracting Command is ", extractCommand 
    extractStatus = os.system(extractCommand)
    os.chdir(currentDir)
    if  extractStatus != 0:
        print "rtos directory extraction was wrong!!!: Command Used ** " + extractCommand + " ** Check log file"  
        sys.exit(-1)
    
    print "List of Extracted files, either with cvs or tar is on ", logFile
    
##############################################################################      
     
def buildRTOS(localDir, currentDir, removeRtosDir, now):    
    
    temporaryDir = localDir + '/rtos'
    BUILD = '/bin/make NO_TAR_FILE=1 build '
    logFile  = currentDir + '/RTOSbuild.log'
    print "Log File for the build is ", logFile
    if os.environ.has_key('INTROOT'):
        print "$INTROOT is defined, RTOS will be installed under " + os.environ['INTROOT'] + '/bin'
    os.chdir(currentDir)
    command = 'make NO_TAR_FILE=1 build >& ' +  logFile
    #print "build Command is ", command 
    print "Build Log file is ", logFile
    os.chdir(temporaryDir)
    buildStatus = os.system(command)
    os.chdir(currentDir)
    
    # If required then remove the rtos build directory
    if removeRtosDir and buildStatus == 0:
        print "Removing as required the build directory " + temporaryDir
        command = '/bin/rm -rf ' + temporaryDir
        os.system(command)
    else:
        if buildStatus != 0:
            print "Build returned an error: if -c options specified not removing temporary directory"
        
##############################################################################      
    
def checkInput():  
    # 
    import getopt
    
    # By default the clean option is not set
    # So the temporary structure used to build rtos 
    # under localDir/rtos is not removed after the build
    removeRtosDir = False
    
    # Check number of parameters passed
    nparams = len(sys.argv)
    
    # without options the default is to work locally on a file and use $ACSROOT/config/rtos.src.tar.gz
    # in the configuration file
    
    #print "Parameter Number =",  nparams
    if nparams == 1  or nparams >4:      
        usage()
        sys.exit(-1)

    # Possible options 
    # -f or --file <absolutpath>: Select tar file to use for rtos source tree
    # -t or --tag <tag> : Select a tag to check out with cvs (no tag = HEAD)
    # -c or --clean : Remove the temporary directory used to build rtos after the build
    # -h or --help
    if sys.argv[1] == '-c':
        removeRtosDir = True
        sys.argv.remove('-c')
 
    try:
        opts, args = getopt.getopt(sys.argv[1:], "f:t:h", ["file","tag","help"])
        #print "opts = " + str(opts) + " args = " + str(args)
    except getopt.GetoptError, errorMessage:
        #print dir(errorMessage)
        # Parse the exception
        option  = errorMessage.opt
        message = errorMessage.msg
        
        # First let's exclude forbidden parameters are used
        if option != 't' and option != 'f' and option != 'h':
            print "Option ", option, " is not allowed here !"
            usage()
            sys.exit(-1)
            
        # Then check if you specified -f option without parameters
        # then set up a default rots source tar file
        if  option == 'f':
            defaultSource = os.environ['ACSROOT'] + '/config/rtos.src.tar.gz'
            if os.access(defaultSource, os.R_OK) and os.path.isfile(defaultSource):
                return(option, defaultSource, removeRtosDir)
            else:
                print "RTOS Source Tar File '",  defaultSource, "' does not exist or is not readable:\n"
                sys.exit(1)
        # Then check if you specified -t option without parameters
        # then set up a default tag
        if  option == 't':
            defaultTag = 'HEAD'
            return(option, defaultTag, removeRtosDir)
            
        

    # If everything is fine then we specified option + parameter
    # print opts
  
    for input,param in opts:
        if input == "-f":
            # Get rtos source from a local tar file
            sourceFile = param
            if os.access(sourceFile, os.R_OK) and os.path.isfile(sourceFile):
                input = 'f'
                return(input, sourceFile, removeRtosDir)
            else:
                print "RTOS Source Tar File '",  sourceFile, "' does not exist or is not readable:\n"
                sys.exit(1)
            
        # If parameter is -t simply return the tag to main
        if input == "-t":
            tag = param
            input= 't'
            return(input, tag, removeRtosDir)
                
        if input in ("-h", "--help"):
            usage()
            sys.exit(-2)
    
   
    # If it gets there there is some error
    print "You are not using right parameters"
    usage()
    sys.exit(-2)
        
##############################################################################      
 
def usage():
    scriptName = os.path.basename(sys.argv[0]) 
    print "\n\n************************************ " + scriptName + " Usage *********************************************************"
    print "Download and build rtos on the local machine"
    print "Usage is :"
    print "**********************************************************************************************************************"
    print scriptName+ " [-c|--clean] [-f|--file] <rtos source tar file> [-t|--tag]  [-h|--help]\n"
    print "Where: \n"
    print " -c or --clean                          : Remove the temporary directed used to build rtos\n"
    print " -f or --file <rtos source file path>   : build RTOS untarring the selected local file "
    print "                                          If no file is provided, the default is $ACSROOT/config/rtos.src.tar.gz"
    print " -t or --tag <TAG>                      : Use the selected tag to check out RTOS source"
    print "                                          If no tag is provided then the HEAD is used"
    print " -h or --help : print this menu"
    print "you can specify only one of -f, -t, -h parameters\n"
    sys.exit(-2)

# ************************************************************************************************************88
# Main
# ************************************************************************************************************88
#

localDir = "/tmp"
currentDir = os.getcwd()

now = timeStamp()

(option, param, removeRtosDir) = checkInput()
print option

#print "Option = ", option, " Param = ", param

checkConf(localDir)

extractSource(option, param, localDir, currentDir, now)

#print removeRtosDir
buildRTOS(localDir, currentDir, removeRtosDir, now )