"""
Copyright 2020 VMware, Inc.
All rights reserved. -- VMware Confidential
"""

import os
from ..PayloadTar import PayloadTar

class ReservedVibTar(PayloadTar):
   """Implements a representation of a gzipped tar which can be used to cache
      reserved vibs.
   """

   PAYLOAD_PREFIX = "var/db/reservedVibs"

   def __init__(self, filepath):
      """Class constructor.
            Parameters:
              * filepath - Must be either a string, giving the path of a file
                           to write the gzipp'ed tar output, or a file-like
                           object where gzipp'ed tar output will be written.
                           In either case, the file or file-like object must
                           be writable.
      """
      # The PayloadTar class manages the tar file.
      super(ReservedVibTar, self).__init__(filepath)

   def AddVib(self, localPath, tarFilePath):
      """Add a vib to the tar. The method accepts the full path to the vib
         location, and a path in the tar where the vib needs to be saved.
         Internally, it creates a file object, finds the size of vib and uses
         _AddFile to write the vib.
      """
      size = os.stat(localPath).st_size
      head, tail = os.path.split(tarFilePath)
      tarDir = os.path.join(self.PAYLOAD_PREFIX, head)
      with open(localPath, 'rb') as fObj:
         self._AddFile(tarDir, tail, size, fObj)

