#!/usr/bin/python
import os
import subprocess
import smtplib
from email.mime.text import MIMEText

HOST_TO_BACKUP       = "mathux.dyndns.org"
GITOLITE_DEPOT_PATH  = "/srv/share/mathieu/gitolite-admin/"
BACKUP_DIR           = "/srv/share/mathieu/Backups/Git"
UPDATE_CMD           = "git remote update"
MIRROR_CMD           = "git clone --mirror git@"+HOST_TO_BACKUP+":"
EMAIL_TO             = "mathieu@mathux.dyndns.org"
EMAIL_SERVER         = "localhost"
EMAIL_ORI            = "backup@mathux.dyndns.org"


def sendMail(stdOut,stdErr,repo):
    email_text = "Error when sync "+repo+"\n"
    email_text += "stdOut :"+stdOut+"\n\n"
    email_text += "stdErr :"+stdErr+"\n\n"

    msg            = MIMEText(email_text)
    msg['Subject'] = "Erreur Synchro" +repo
    msg['From']    = EMAIL_ORI

    for dest in EMAIL_TO.split(","):
        msg['To'] = dest
    s = smtplib.SMTP(EMAIL_SERVER)
#    s.login(config["EMAIL_ORI"],config["EMAIL_PASS"])
    s.sendmail(EMAIL_ORI, dest, msg.as_string())
    s.quit()

def getRepoList():
    gitolite_conf = open(os.path.join(GITOLITE_DEPOT_PATH, "conf/gitolite.conf"), 'r')
    content = gitolite_conf.read()
    repo = []
    for line in content.split("\n") :
        if line.startswith("repo"):
            repo.append(line.split(" ")[1])
    return repo


repoToBackup = getRepoList()

for repo in repoToBackup:
    repo_path = os.path.join(BACKUP_DIR, repo+".git")
    stdOut = ""
    stdErr = ""
    ret = 0
    if os.path.exists(repo_path):
        os.chdir(repo_path)
        proc = subprocess.Popen(UPDATE_CMD,
                                shell=True,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        (stdOut, stdErr) = proc.communicate()
        ret = proc.returncode
    else:
        os.chdir(BACKUP_DIR)
        proc = subprocess.Popen(MIRROR_CMD+repo,
                                shell=True,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        (stdOut, stdErr) = proc.communicate()
        ret = proc.returncode
    if ret:
        sendMail(stdOut, stdErr, repo)
