
from __future__ import absolute_import

from vdsm.common import cmdutils
from vdsm.common import commands
from vdsm import constants

_curl = cmdutils.CommandPath("curl",

CURL_OPTIONS = ["-q", "--silent", "--fail", "--show-error"]


class CurlError(Exception):
    def __init__(self, ecode, stdout, stderr, message=None):
        self.ecode = ecode
        self.stdout = stdout
        self.stderr = stderr
        self.message = message

    def __str__(self):
        return "ecode=%s, stdout=%s, stderr=%s, message=%s" % (
            self.ecode, self.stdout, self.stderr, self.message)


def _headersToOptions(headers):
    options = []
    for k, v in headers.iteritems():
        options.extend(("--header", "%s: %s" % (k, v)))
    return options


def head(url, headers={}):
    cmd = [_curl.cmd] + CURL_OPTIONS + ["--head", url]

    cmd.extend(_headersToOptions(headers))
    rc, out, err = commands.execCmd(cmd)

    if rc != 0:
        raise CurlError(rc, out, err)

    return dict([x.split(": ", 1) for x in out[1:-1]])


def download(url, path, headers={}):
    cmd = [constants.EXT_CURL_IMG_WRAP, "--download"]
    cmd.extend(_headersToOptions(headers) + [path, url])

    rc, out, err = commands.execCmd(cmd)

    if rc != 0:
        raise CurlError(rc, out, err)


def upload(url, path, headers={}):
    cmd = [constants.EXT_CURL_IMG_WRAP, "--upload"]
    cmd.extend(_headersToOptions(headers) + [path, url])

    rc, out, err = commands.execCmd(cmd)

    if rc != 0:
        raise CurlError(rc, out, err)
