#!/usr/bin/env python3
import oss2
import sys
import os
import time
import argparse

oss_ak = 'LTAI5tC2qXGxwHZUZP7DoD1A'
oss_sk = 'qPo9O6ZvEfqo4t8oflGEm0DoxLHJhm'

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--dir', '-d', type=str, default='/data/qrs/tree', help='directory of qrs')
    return parser.parse_args()

def all_qrs(dir):
    for r, ds, fs in os.walk(dir):
        for f in fs:
            if f.endswith('.jpg'):
                yield os.path.join(r, f)

def main():
    args = parse_args()
    auth = oss2.Auth(oss_ak, oss_sk)
    endpoint = 'https://oss-cn-guangzhou.aliyuncs.com'
    bucket = oss2.Bucket(auth, endpoint, 'emblem-qrs')

    rootdir = args.dir

    aqrs = list(all_qrs(rootdir))
    total = len(aqrs)
    done = 0
    print(f'total: {total}')
    for qr in aqrs:
        qrcode = os.path.basename(qr).split('.')[0]
        prefix = qrcode[:2]
        key = f'v5/{prefix}/{qrcode}.jpg'
        for i in range(3):
            try:
                print(f'{done}/{total} {qr} -> {key}')
                bucket.put_object_from_file(key, qr)
                done += 1
                break
            except Exception as e:
                print(f'{e}')
                time.sleep(1)

if __name__ == '__main__':
    main()