# Path: lava_dispatcher/action.py
# class InfrastructureError(LAVAError):
#     """
#     Exceptions based on an error raised by a component of the
#     test which is neither the LAVA dispatcher code nor the
#     code being executed on the device under test. This includes
#     errors arising from the device (like the arndale SD controller
#     issue) and errors arising from the hardware to which the device
#     is connected (serial console connection, ethernet switches or
#     internet connection beyond the control of the device under test).
# 
#     Use LAVABug for errors arising from bugs in LAVA code.
#     """
#     error_help = "InfrastructureError: The Infrastructure is not working " \
#                  "correctly. Please report this error to LAVA admins."
#     error_type = "Infrastructure"
# 
# class JobError(LAVAError):
#     """
#     An Error arising from the information supplied as part of the TestJob
#     e.g. HTTP404 on a file to be downloaded as part of the preparation of
#     the TestJob or a download which results in a file which tar or gzip
#     does not recognise.
#     """
#     error_help = "JobError: Your job cannot terminate cleanly."
#     error_type = "Job"
# 
# Path: lava_dispatcher/utils/contextmanager.py
# @contextmanager
# def chdir(path):
#     pwd = None
#     try:
#         pwd = os.getcwd()
#         os.chdir(path)
#         yield
#     finally:
#         if pwd is not None:
#             os.chdir(pwd)
# 
# Path: lava_dispatcher/utils/shell.py
# def which(path, match=os.path.isfile):
#     exefile = _which_check(path, match)
#     if not exefile:
#         raise InfrastructureError("Cannot find command '%s' in $PATH" % path)
# 
#     if os.stat(exefile).st_mode & S_IXUSR != S_IXUSR:
#         raise InfrastructureError("Cannot execute '%s' at '%s'" % (path, exefile))
# 
#     return exefile


import os
import subprocess
import tarfile
from lava_dispatcher.action import (
    InfrastructureError,
    JobError
)
from lava_dispatcher.utils.contextmanager import chdir
from lava_dispatcher.utils.shell import which


def compress_file(infile, compression):
    if not compression:
        return infile
    if compression not in compress_command_map.keys():
        raise JobError("Cannot find shell command to compress: %s" % compression)

    # Check that the command does exists
    which(compress_command_map[compression].split(" ")[0])

    with chdir(os.path.dirname(infile)):
        cmd = "%s %s" % (compress_command_map[compression], infile)
        try:
            # safe to use shell=True here, no external arguments
            subprocess.check_output(cmd, shell=True)
            return "%s.%s" % (infile, compression)
        except (OSError, subprocess.CalledProcessError) as exc:
            raise InfrastructureError('unable to compress file %s: %s' % (infile, exc))


def decompress_file(infile, compression):
    if not compression:
        return infile
    if compression not in decompress_command_map.keys():
        raise JobError("Cannot find shell command to decompress: %s" % compression)

    # Check that the command does exists
    which(decompress_command_map[compression])


# Path: lava_dispatcher/action.py
# class InfrastructureError(LAVAError):
#     """
#     Exceptions based on an error raised by a component of the
#     test which is neither the LAVA dispatcher code nor the
#     code being executed on the device under test. This includes
#     errors arising from the device (like the arndale SD controller
#     issue) and errors arising from the hardware to which the device
#     is connected (serial console connection, ethernet switches or
#     internet connection beyond the control of the device under test).
# 
#     Use LAVABug for errors arising from bugs in LAVA code.
#     """
#     error_help = "InfrastructureError: The Infrastructure is not working " \
#                  "correctly. Please report this error to LAVA admins."
#     error_type = "Infrastructure"
# 
# class JobError(LAVAError):
#     """
#     An Error arising from the information supplied as part of the TestJob
#     e.g. HTTP404 on a file to be downloaded as part of the preparation of
#     the TestJob or a download which results in a file which tar or gzip
#     does not recognise.
#     """
#     error_help = "JobError: Your job cannot terminate cleanly."
#     error_type = "Job"
# 
# Path: lava_dispatcher/utils/contextmanager.py
# @contextmanager
# def chdir(path):
#     pwd = None
#     try:
#         pwd = os.getcwd()
#         os.chdir(path)
#         yield
#     finally:
#         if pwd is not None:
#             os.chdir(pwd)
# 
# Path: lava_dispatcher/utils/shell.py
# def which(path, match=os.path.isfile):
#     exefile = _which_check(path, match)
#     if not exefile:
#         raise InfrastructureError("Cannot find command '%s' in $PATH" % path)
# 
#     if os.stat(exefile).st_mode & S_IXUSR != S_IXUSR:
#         raise InfrastructureError("Cannot execute '%s' at '%s'" % (path, exefile))
# 
#     return exefile


# Path: lava_dispatcher/utils/compression.py
import os
import subprocess
import tarfile
from lava_dispatcher.action import (
    InfrastructureError,
    JobError
)
from lava_dispatcher.utils.contextmanager import chdir
from lava_dispatcher.utils.shell import which



def compress_file(infile, compression):
    if not compression:
        return infile
    if compression not in compress_command_map.keys():
        raise JobError("Cannot find shell command to compress: %s" % compression)

    # Check that the command does exists
    which(compress_command_map[compression].split(" ")[0])

    with chdir(os.path.dirname(infile)):
        cmd = "%s %s" % (compress_command_map[compression], infile)
        try:
            # safe to use shell=True here, no external arguments
            subprocess.check_output(cmd, shell=True)
            return "%s.%s" % (infile, compression)
        except (OSError, subprocess.CalledProcessError) as exc:
            raise InfrastructureError('unable to compress file %s: %s' % (infile, exc))


def decompress_file(infile, compression):
    if not compression:
        return infile
    if compression not in decompress_command_map.keys():
        raise JobError("Cannot find shell command to decompress: %s" % compression)

    # Check that the command does exists
    which(decompress_command_map[compression])


    with chdir(os.path.dirname(infile)):