#!/usr/bin/env python

import os
import sys

import boto3
import botocore
from botocore.utils import fix_s3_host

bucket_name = os.getenv('BUCKET_NAME')

if os.getenv('DATABASE_STORAGE') == "s3":
    conn = boto3.resource('s3')
else:
    conn = boto3.resource('s3', endpoint_url=os.getenv('S3_URL'))
    # stop boto3 from automatically changing the endpoint
    conn.meta.client.meta.events.unregister('before-sign.s3', fix_s3_host)

exists = True
try:
    conn.meta.client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as e:
    # If a client error is thrown, then check that it was a 404 error.
    # If it was a 404 error, then the bucket does not exist.
    error_code = int(e.response['Error']['Code'])
    if error_code == 404:
        exists = False
    else:
        raise

if not exists:
	conn.create_bucket(Bucket=bucket_name)
