#!/usr/bin/env python
import os
import time
import tarfile
import argparse
from config import *
from mailer import sendto
from chrono import str_now
from clients import conn_redis
'''
redis backup workflow

0, preparation: setting "appendonly no"
1, login redis (slave redis is preferred)
2, execute snapshot
3, compress .rdb
4, send rdb to email (or other secure remote server)

error log is a plus.
'''


def create_tar_gz(f, files):
    """
    compress files into one tar.gz

    :param f: dest filename  xxx.tar.gz
    :param files: []
    :return: None
    """
    with tarfile.open(name=f, mode='w:gz') as tar:
        for file in files:
            tar.add(file)


def worker_impl(subject):
    rds = conn_redis(rds_slave_host, rds_slave_port, '', rds_slave_password, rds_db_game)
    rds.bgsave()
    time.sleep(60)
    create_tar_gz(dest_tar_file, [rds_rdb])
    sendto(email_backup, subject, 'there should be a attachment', dest_tar_file)
    os.unlink(dest_tar_file)
    rds.close()


def main():
    parser = argparse.ArgumentParser(description='timer task for checking if user active')
    parser.add_argument('-s', '--subject', action='store', dest='subject', default='backup', type=str, metavar='subject', help='set subject of backup mail')
    parser.add_argument('-i', '--interval', action='store', dest='interval', default=60*60*12, type=int, metavar='interval', help='set interval of execution')
    args = parser.parse_args()

    while True:
        try:
            print('started at ', str_now())
            worker_impl(args.subject,)
            print('done.', str_now())
        except Exception as e:
            print('exception: ', e)
        time.sleep(args.interval)     # in second


if __name__ == '__main__':
    main()
