#coding=utf-8

import commands
import datetime
import paramiko

'''
must exec with root
'''

def execmd(cmdString):
    status, output = commands.getstatusoutput(cmdString)
    return status, output

def scp(file, remote_file ,ssh_host, ssh_port, ssh_user, ssh_pwd):
    transport = paramiko.Transport((ssh_host, ssh_port))
    transport.connect(username=ssh_user, password=ssh_pwd)
    sftp = paramiko.SFTPClient.from_transport(transport)
    sftp.put(file, remote_file)
    transport.close()

def backup_scp(
    db_host,
    db_port,
    db_user,
    db_pwd,
    db_name,
    ssh_host,
    ssh_port,
    ssh_user,
    ssh_pwd,
    ssh_dir
):
    cmd = 'mysqldump --skip-lock-tables --single-transaction --flush-logs --hex-blob --master-data=2 -h%s -P%s -u%s -p%s  --databases %s > %s.sql' % (
        db_host,
        db_port,
        db_user,
        db_pwd,
        db_name,
        db_name
    )
    execmd(cmd)
    cmd = 'tar zcvf %s.tar.gz ./%s.sql' % (db_name, db_name)
    execmd(cmd)
    file = "%s.tar.gz.%s" % (db_name,  datetime.date.today())
    cmd = 'mv %s.tar.gz %s' % (db_name, file)
    execmd(cmd)
    if ssh_dir[-1] != '/':
        ssh_dir = ssh_dir + '/'
    remote_file = ssh_dir + file
    scp(
        file = file,
        remote_file = remote_file,
        ssh_host = ssh_host,
        ssh_port = ssh_port,
        ssh_user = ssh_user,
        ssh_pwd = ssh_pwd
    )
    return True