#!/usr/bin/env python
# coding=UTF-8

__author__ = "Pierre-Yves Langlois"
__copyright__ = "https://github.com/pylanglois/uadm/blob/master/LICENCE"
__credits__ = ["Pierre-Yves Langlois","Francois Vaillancourt"]
__license__ = "BSD"
__version__ = "1.0"
__maintainer__ = "Pierre-Yves Langlois"
__status__ = "Production"

"""
This script will backup folders using duplicity and a samba destination. 
Full backup every 1st of the month, deleting backup older than 1 month

Usage uadm_smb_backup.py /dir1,/path/dir2,...

Modify the script to your needs with SMB_DEST, MOUNT_PATH and CRED_PATH
"""

import sys
import os
from datetime import datetime

from uadm.uadmcore import *

mod_conf( {
    "SMB_DEST" : "//your-smb-server.example.com/backup_server$",
    "MOUNT_PATH" : "/media/backup_server",
    "CRED_PATH" : "/root/.credentials",
}, override=False)

class NotADirException(Exception):
    pass

def extract_dir(csv_dirs):
    csv_dirs = csv_dirs.split(",")
    all_dirs = True

    for d in csv_dirs:
        if not os.path.isdir(d):
            all_dirs = False
            break

    if not all_dirs:
        msg = "Params must be directories... params: %s" % csv_dirs
        raise NotADirException(msg)

    return csv_dirs

def build_duplicity_folder_list(dirs_list):
    duplicity_dirs_list = ""
    for d in dirs_list:
        duplicity_dirs_list += "--include=%s " % d
    return duplicity_dirs_list

#if __name__ == "__main__":
def run(args = []):
    if len(args) != 2:
        msg = u"Missing or extra parameter. Usage: uadm_xxx.py /etc,/var/www,/dir123"
        l['l'].error(msg)
        send_error_report(msg)
        exit(1)
    else:
        try:
            pathsToBackup = extract_dir(args[1])
            duplicity_dirs_list = build_duplicity_folder_list(pathsToBackup)
            path_dest = "%s/%s" % (CONF_MAP["MOUNT_PATH"], HOST_INFO["hostname"])

            cmd_list = [
                
                #MOUNT SMB DESTINATION
                cfb(str("""
                        mount   -t cifs 
                                -o credentials=%(cred_path)s,iocharset=utf8,codepage=unicode,unicode 
                                %(smb_dest)s 
                                %(mount_path)s
                        """ % 
                        {
                            "cred_path": CONF_MAP["CRED_PATH"],
                            "mount_path": CONF_MAP["MOUNT_PATH"],
                            "smb_dest": CONF_MAP["SMB_DEST"],
                        }
                )),

                #CLEANUP DUPLICITY DEST
                cfb(str("""
                        /usr/bin/duplicity 
                            --no-encryption 
                            cleanup 
                            --extra-clean 
                            --force 
                            file://%(path_dest)s/
                        """ % 
                        {
                            "path_dest": path_dest,
                        }
                )),

                #DELETE OLD DUPLICITY BACKUP
                cfb(str("""
                        /usr/bin/duplicity 
                            --no-encryption 
                            remove-older-than 1M 
                            -v9 
                            --force 
                            file://%(path_dest)s/
                        """ % 
                        {
                            "path_dest": path_dest,
                        }
                )),

                #BACKUP JOB
                cfb(str("""
                        /usr/bin/duplicity 
                            --no-encryption 
                            %(full)s 
	                        --volsize=250 
                            %(include)s 
                            --exclude=/** 
                            / 
                            file://%(path_dest)s/ 
                        """ % 
                        {
                            "full": "full" if datetime.now().day == 1 else "",
                            "include": duplicity_dirs_list,
                            "path_dest": path_dest,
                        }
                )),
            ]

            #exec_cmd_list(cmd_list)

        except NotADirException, e:
            msg = u"Something went wrong: %s" % unicode(e)
            l['l'].exception(msg)
            send_error_report(msg)
            exit(1)
        except:
            msg = u"Something went wrong."
            l['l'].exception(msg)
            send_error_report(msg)
            exit(1)
        finally:
            exec_cmd_list([
                #UMOUNT SMB DEST
                "umount %s" %  CONF_MAP["MOUNT_PATH"],
            ])
            



