#
# Created as part of the StratusLab project (http://stratuslab.eu),
# co-funded by the European Commission under the Grant Agreement
# INFSO-RI-261552."
#
# Copyright (c) 2011, SixSq Sarl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import tempfile
import copy

from stratuslab import Util
from stratuslab.ManifestInfo import ManifestInfo
from stratuslab.Signator import Signator
from stratuslab.ConfigHolder import ConfigHolder
from stratuslab.AuthnCommand import P12Certificate

from stratuslab.marketplace.Uploader import Uploader
from stratuslab.marketplace.Downloader import Downloader

from Util import Util as MarketplaceUtil

class Deprecator(object):

    @staticmethod
    def buildDeprecatorParser(parser):
        parser.usage = '''usage: %prog [options] <image id>'''

        MarketplaceUtil.addEndpointOption(parser)
        P12Certificate.addOptions(parser)

        parser.add_option('--email', dest='email',
                help='email address of endorser of metadata entry',
                default='')

        parser.add_option('--created', dest='created',
                help='date of metadata entry to be deprecated, latest entry will be deprecated if not provided',
                default='')

        parser.add_option('--reason', dest='reason',
                help='Comment to append to deprecation',
                default='This image has been deprecated', metavar='TEXT')

    @staticmethod
    def checkDeprecatorOptions(options, parser):
        MarketplaceUtil.checkEndpointOption(options)

        if not P12Certificate.checkOptions(options):
            parser.error('Missing credentials. Please provide %s' % P12Certificate.optionString)

        if not options.email:
            parser.error('Missing email address. Please provide email of endorser')

    def __init__(self, configHolder=ConfigHolder()):
        self.configHolder = configHolder
        self.deprecated_xml = '<slterms:deprecated>%(reason)s</slterms:deprecated>'

        configHolder.assign(self)

        self.manifestObject = None
        self.uploader = Uploader(configHolder)
        self.downloader = Downloader(configHolder)

    def deprecate(self, imageId):
        tempMetadataFilename = tempfile.mktemp()
        tempDeprecatedMetadataFilename = tempfile.mktemp()
        try:
            imageURI = imageId + '/' + self.email
            if len(self.created) != 0:
                imageURI = imageURI + '/' + self.created

            self.manifestObject = self.downloader._getManifest(imageId, tempMetadataFilename)
            self.manifestObject.__dict__.update({'deprecated':self._getDeprecatedAsXml()})
            manifestText = self.manifestObject.build()
            file(tempDeprecatedMetadataFilename, 'w').write(manifestText)
            signator = Signator(tempDeprecatedMetadataFilename, self.configHolder)
            isError = signator.sign()
            self.uploader.upload(tempDeprecatedMetadataFilename)
        finally:
            try:
                os.unlink(tempMetadataFilename)
                os.unlink(tempDeprecatedMetadataFilename)
                os.unlink(tempDeprecatedMetadataFilename+'.orig')
            except:
                pass

    def _getDeprecatedAsXml(self):
        joint = '\n        '
        return joint.join([copy.copy(self.deprecated_xml) % {'reason':self.reason}])

@@ -1140,16 +1140,44 @@
 ceUtil%0A%0A
+etree = Util.importETree()%0A%0A
 class De
@@ -2432,154 +2432,43 @@
     
-self.deprecated_xml = '%3Cslterms:deprecated%3E%25(reason)s%3C/slterms:deprecated%3E'%0A%0A        configHolder.assign(self)%0A%0A        self.manifestObject = None
+%0A        configHolder.assign(self)%0A
 %0A   
@@ -2881,29 +2881,39 @@
     
-self.manifestObject =
+# Get metadata file%0A           
  sel
@@ -2943,18 +2943,19 @@
 st(image
+UR
 I
-d
 , tempMe
@@ -2986,141 +2986,660 @@
     
-self.manifestObject.__dict__.update(%7B'deprecated':self._getDeprecatedAsXml()%7D)%0A            manifestText = self.manifestObject.build()
+%0A            # Strip signature%0A            xml = etree.ElementTree(file=tempMetadataFilename)%0A            root = xml.getroot()%0A            descriptionElement = root.find('.//%7B%25s%7DDescription' %25 ManifestInfo.NS_RDF)%0A%0A            signatureElement = root.find('.//%7B%25s%7DSignature' %25 'http://www.w3.org/2000/09/xmldsig#')%0A            signatureElement.getparent().remove(signatureElement)%0A            %0A            xml._setroot(descriptionElement.getparent())%0A%0A            # Add deprecated entry%0A            elem = etree.Element('%7B%25s%7D%25s' %25 (ManifestInfo.NS_SLTERMS, 'deprecated'))%0A            elem.text = self.reason%0A            descriptionElement.append(elem)%0A
 %0A   
@@ -3647,19 +3647,24 @@
         
-fil
+xml.writ
 e(tempDe
@@ -3693,32 +3693,108 @@
 me, 
-'w').write(manifestText)
+standalone=False, encoding=%22utf-8%22, xml_declaration=True)%0A            %0A            # Sign and upload
 %0A   
@@ -4228,153 +4228,4 @@
 ss%0A%0A
-    def _getDeprecatedAsXml(self):%0A        joint = '%5Cn        '%0A        return joint.join(%5Bcopy.copy(self.deprecated_xml) %25 %7B'reason':self.reason%7D%5D)%0A

Change deprecation command to modify the xml directly instead of using ManifestInfo