#!/usr/bin/env python3
# coding:utf-8

import tarfile


msg1201 = 'unknown compression: \'{0}\''
msg1202 = 'source path does not exist: \'{0}\''
msg1203 = 'destination file already exists: \'{0}\''
msg1204 = 'opening tar file for writing: \'{0}\''
msg1205 = 'adding files from: \'{0}\''
msg1206 = 'unable to create tar file: \'{0}\''
msg1207 = 'compression error: \'{0}\''
msg1208 = 'done writing: \'{0}\''


class TAR():

	def tarPath(self, src, dst, arcname=None, comp='tgz'):

		file_ext = {
			'tgz' : '.tar.gz',
			'tbz2' : '.tar.bz2',
			'none' : '.tar',
			}

		tar_mode = {
			'tgz' : 'w:gz',
			'tbz2' : 'w:bz2',
			'none' : 'w',
			}

		try:
			f_name = dst + file_ext[comp]

		except KeyError:
			self.logger.error(msg1201.format(comp))
			return False

		if not self.client_l.isdir(src):
			self.logger.error(msg1202.format(src))
			return False

		if self.client_l.exists(f_name):
			self.logger.error(msg1203.format(f_name))
			return False

		try:
			self.logger.debug(msg1204.format(f_name))

			with tarfile.open(f_name, tar_mode[comp]) as tar_file:
				self.logger.debug(msg1205.format(src))
				tar_file.add(src, arcname=arcname)

		except IOError:
			self.logger.error(msg1206.format(f_name))
			return False

		except tarfile.CompressionError as key:
			self.logger.error(msg1207.format(key))
			return False

		self.logger.debug(msg1208.format(f_name))
		return True


