# coding: utf-8
from datetime import datetime
from dateutil import tz
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import os, tarfile
import smtplib


to_zone = tz.gettz('Asia/Shanghai')
localtime = datetime.now(tz=to_zone)


def make_targz(output_filename, source_dir):
    """
    一次性打包目录为tar.gz
    :param output_filename: 压缩文件名
    :param source_dir: 需要打包的目录
    :return:
    """
    try:
        with tarfile.open(output_filename, "w:gz") as tar:
            tar.add(source_dir, arcname=os.path.basename(source_dir))

        return True
    except Exception as e:
        print(e)
        return False


def send_email(file_name):
    def _format_addr(s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))

    smtp_server = 'smtp.gmail.com'
    smtp_port = 587
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    # 剩下的代码和前面的一模一样:
    # server.set_debuglevel(1)

    from_addr = ''
    to_addr = ''
    to_zone = tz.gettz('Asia/Shanghai')
    localtime = datetime.now(tz=to_zone)

    msg = MIMEMultipart()
    msg['From'] = _format_addr('Vaultwarden <%s>' % from_addr)
    msg['To'] = _format_addr('<%s>' % to_addr)
    msg['Subject'] = Header('bitwarden 备份 %s' % localtime.strftime('%Y-%m-%d'), 'utf-8').encode()

    # 邮件正文是MIMEText:
    msg.attach(MIMEText('backup file attached', 'plain', 'utf-8'))

    # 添加附件就是加上一个MIMEBase，从本地读取一个图片:
    with open(file_name, 'rb') as f:
        # 设置附件的MIME和文件名
        mime = MIMEBase('tar.gz', 'tar.gz', filename=file_name)
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename=file_name)
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(f.read())
        # 用Base64编码:
        encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)

    server.login(from_email, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()


if __name__ == '__main__':
    file_name = '/root/develop/vaultwarden/backup/bitwarden-%s.tar.gz' % localtime.strftime('%Y-%m-%d')
    if make_targz(file_name, '/root/develop/vaultwarden/vw-data'):
        send_email(file_name)
