# plugs/backup.py
#
#

""" backup plug .. only make backup if filesize has grown """

__copyright__ = 'this file is in the public domain'

from gozerbot.config import config
from gozerbot.generic import rlog, handle_exception, filesize
from gozerbot.datadir import datadir
from gozerbot.periodical import hourly, periodical
import os, shutil, time

backupdir = config['backupdir'] or 'backup'
filesizes = {}
stopbackup = False

if not os.path.isdir(backupdir):
    os.mkdir(backupdir)
backupfiles = os.listdir(backupdir)
for i in backupfiles:
    if i.endswith('.tmp'):
        continue
    filesizes[i] = filesize(backupdir + os.sep + i)

def init():
    backup()
    return 1

def shutdown():
    global stopbackup
    stopbackup = True
    time.sleep(3)
    periodical.kill()
    return 1

@hourly
def backup():
    try:
        # get list of files in datadir
        datafiles = os.listdir(datadir)
        # for each file check data size and if file has grown copy it
        for datafile in datafiles:
            if stopbackup:
                break
            dfilename = datadir + os.sep + datafile
            if dfilename.endswith('.tmp'):
                continue
            bfilename = backupdir + os.sep + datafile
            if os.path.isdir(dfilename):
                continue
            doit = 0
            try:
                dsize = filesize(datadir + os.sep + datafile)
            except OSError:
                continue
            if datafile not in filesizes:
                doit = 1
            elif dsize > filesizes[datafile]:
                doit = 1
            if doit:
                rlog(5, 'backup', 'making backup of %s' % datafile)
                shutil.copyfile(dfilename, bfilename)
                filesizes[datafile] = dsize
                time.sleep(2)
    except Exception, ex:
        handle_exception()
