#
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# 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 Common Public License for
# full details.
#
"""
Contains the functions which derive a package and commit the
resulting packages to the repository.
"""

import os

from conary.lib import log

def derive(handle, troveToDerive):
    """
        Performs all the commands necessary to create a derived recipe.
        First it shadows the package, then it creates a checkout of the shadow
        and converts the checkout to a derived recipe package.

        @param handle: rbuild handle containing information about the
        active stage.
        @param troveToDerive: troveTuple of binary which we wish to derive
    """

    targetLabel = handle.getProductStore().getActiveStageLabel()
    troveName = troveToDerive[0]
    # displaying output along the screen allows there to be a record
    # of what operations were performed.  Since this command is
    # an aggregate of several commands I think that is appropriate,
    # rather than simply using a progress callback.
    log.info('Shadowing %s=%s[%s] onto %s' % (troveToDerive[0],
                                             troveToDerive[1],
                                             troveToDerive[2],
                                             targetLabel))
    conaryFacade = handle.facade.conary

    conaryFacade.shadowSourceForBinary(troveToDerive[0],
                                       troveToDerive[1],
                                       troveToDerive[2],
                                       targetLabel)
    troveName = troveName.split(':')[0]
    conaryFacade.checkout(troveName, targetLabel)
    _writeDerivedRecipe(conaryFacade, troveName, directory=troveName)

    extractDir = '%s/%s/_ROOT_' % (os.getcwd(), troveName)
    log.info('extracting files from %s=%s[%s]' % troveToDerive)
    troveName, version, flavor = troveToDerive
    conaryFacade.checkoutBinaryPackage(troveName, version, flavor,
                                       extractDir)

def _writeDerivedRecipe(conaryFacade, troveName, directory):
    recipeName = troveName + '.recipe'
    recipePath = os.path.realpath(directory + '/' + recipeName)

    log.info('Removing extra files from checkout')
    conaryFacade._removeNonRecipeFilesFromCheckout(recipePath)
    log.info('Rewriting recipe file')
    recipeClass = conaryFacade._loadRecipeClassFromCheckout(recipePath)
    derivedRecipe = """
class %(className)s(DerivedPackageRecipe):
    name = '%(name)s'
    version = '%(version)s'

    def setup(r):
        pass

""" % dict(className=recipeClass.__name__,
           name=recipeClass.name,
           version=recipeClass.version)
    open(recipePath, 'w').write(derivedRecipe)

@@ -761,20 +761,16 @@
     %22%22%22%0A
-    
     Perf
@@ -833,20 +833,16 @@
 pe.%0A    
-  
-  
 First it
@@ -904,20 +904,16 @@
  shadow%0A
-    
     and 
@@ -964,20 +964,16 @@
 ckage.%0A%0A
-    
     @par
@@ -1030,20 +1030,16 @@
 out the%0A
-    
     acti
@@ -1048,20 +1048,16 @@
  stage.%0A
-    
     @par
@@ -2979,13 +2979,1249 @@
     
-pass%0A
+'''%0A        In this recipe, you can make modifications to the package,%0A        starting with the contents of the parent (upstream) package.%0A        When this package is built, it starts with the contents%0A        of the parent package unpacked in %25%25(builddir)s, and you%0A        can modify those contents, deleting or modifying existing%0A        files.  You can also build new sources and add additional%0A        files to the package.%0A%0A        Examples:%0A%0A        # This appliance has high-memory-use PHP scripts%0A        r.Replace('memory_limit = 8M', 'memory_limit = 32M', '/etc/php.ini')%0A%0A        # This appliance uses PHP as a command interpreter but does%0A        # not include a web server, so remove the file that creates%0A        # a dependency on the web server%0A        r.Remove('/etc/httpd/conf.d/php.conf')%0A%0A        # This appliance requires that a few binaries be replaced%0A        # with binaries built from a custom archive that includes%0A        # a Makefile that honors the DESTDIR variable for its%0A        # install target.%0A        r.addArchive('foo.tar.gz')%0A        r.Make()%0A        r.MakeInstall()%0A%0A        # This appliance requires an extra configuration file%0A        r.Create('/etc/myconfigfile', contents='some data')%0A        '''
 %0A%22%22%22

replace "pass" with useful docstring in new derived recipes (RBLD-31)