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

import os, sys, time, urllib3
from minio import Minio
from minio.lifecycleconfig import Expiration, LifecycleConfig, Rule, Transition
from minio.commonconfig import ENABLED, Filter

def minio_conn(ipaddr, portnum, ac_key, sec_key):
    conn='{}:{}'.format(ipaddr,portnum)
    url='http://{}'.format(conn)
    print(url)
    minio_client = Minio(
    conn, access_key=ac_key, secret_key=sec_key, secure=False,
    http_client=urllib3.ProxyManager(
        url, timeout=urllib3.Timeout.DEFAULT_TIMEOUT,
        retries=urllib3.Retry(
            total=5, backoff_factor=0.2,
                status_forcelist=[
                    500, 502, 503, 504
                ],
        ),
    ),
    )

    return minio_client

def minio_create_buckets(minio_client, bucket_name, days, rule_id="cloudmoa"):
    config = LifecycleConfig(
    [
        Rule(
            ENABLED,
            rule_filter=Filter(prefix=""),
            rule_id=rule_id,
            expiration=Expiration(days=days),
        ),
    ],
    )
    minio_client.set_bucket_lifecycle(bucket_name, config)

def minio_delete_bucket(client, bucket_name):
    client.delete_bucket_lifecycle(bucket_name)

def main():
    s3_url      = os.sys.argv[1].split(':')[0]
    s3_url_port = os.sys.argv[1].split(':')[1]
    minio_user  = os.sys.argv[2]
    minio_pass  = os.sys.argv[3]
    bucket_name = os.sys.argv[4]
    minio_days  = os.sys.argv[5]
    rule_id     = os.sys.argv[6]

    print(s3_url, s3_url_port, minio_user, minio_pass)

    minio_client=minio_conn(s3_url, s3_url_port, minio_user, minio_pass)
    minio_create_buckets(minio_client, bucket_name, minio_days, rule_id)

if __name__ == "__main__":
    try:
        main()
    except Exception as err:
        print("[Usage] minio {url:port} {username} {password} {bucketName} {days} {ruleId}")
        print(err)