#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import re
import argparse
from azure.storage.blob import (BlobServiceClient, StandardBlobTier)

parser = argparse.ArgumentParser()
parser.add_argument('-s', '--storage_account', help='storage account')
parser.add_argument('-c', '--container_name', help='container name')
parser.add_argument('-key', '--key', help='access key or SAS token')
parser.add_argument('-b', '--blob_name', help='blob name')
parser.add_argument('-bf', '--blob_folder', help='upload blob folder if set')
parser.add_argument('-f', '--file_name', help='file name')
parser.add_argument(
    '-t',
    '--tier',
    help='change tier(hot, cool, archive), print tier if unset')

args = parser.parse_args()

credential = getattr(args, 'key')
storage_account = getattr(args, 'storage_account')
container_name = getattr(args, 'container_name')
blob_name = getattr(args, 'blob_name')
blob_folder = getattr(args, 'blob_folder')
file_name = getattr(args, 'file_name')
tier = getattr(args, 'tier')

if tier is not None and tier not in ('hot', 'cool', 'archive'):
    print('tier must in hot, cool, archive or not set')
    exit()

if not storage_account:
    storage_account = os.environ.get('AZURE_STORAGE_ACCOUNT')
if not container_name:
    container_name = os.environ.get('AZURE_CONTAINER_NAME')
if not credential:
    credential = os.environ.get('AZURE_BLOB_KEY')

if not storage_account:
    print(
        'must provide storage_account or environment variable AZURE_STORAGE_ACCOUNT'
    )
    exit()
if not storage_account:
    print(
        'must provide container_name or environment variable AZURE_CONTAINER_NAME'
    )
    exit()
if not storage_account:
    print('must provide access_key or environment variable AZURE_BLOB_KEY')
    exit()

account_url = 'https://{storage_account}.blob.core.windows.net'.format(
    storage_account=storage_account)
service = BlobServiceClient(account_url=account_url, credential=credential)
container = service.get_container_client(container_name)

if not blob_name:
    blob_name = re.sub('.*/', '', file_name)

if blob_name:
    if blob_name.endswith('/'):
        blob_name = blob_name[1:]

if blob_folder:
    if blob_folder.endswith('/'):
        blob_folder = blob_folder[:-1]
    blob_name = blob_folder + '/' + blob_name

blob = container.get_blob_client(blob_name)

with open(file_name, 'rb') as data:
    blob.upload_blob(data)

if tier == 'hot':
    blob.set_standard_blob_tier(StandardBlobTier.Hot)
elif tier == 'cool':
    blob.set_standard_blob_tier(StandardBlobTier.Cool)
elif tier == 'archive':
    blob.set_standard_blob_tier(StandardBlobTier.Archive)
