#!/usr/bin/env python

#import cgitb; cgitb.enable()
import cgi
import os
import os.path
import sys
import re

form = cgi.FieldStorage()

repository = form.getfirst("repository", "")
if repository == "":
    raise "Missing parameter 'repository'"
#

match = re.match("^[-_.A-Za-z0-9]+$", repository)
if not match:
    raise "Illegal value for 'repository'"
#

repository_path = "/svn_repos/" + repository
if not os.path.isdir(repository_path):
    raise "Non-existent 'repository'"
#

pid = os.getpid()

backup_dir  = "bkp_" + str(pid)
backup_file = backup_dir + ".tar"

backup_dir_path  = "/svn_repos/" + backup_dir
backup_file_path = "/svn_repos/" + backup_file

if os.path.isdir(backup_dir_path):
    raise "Backup path already exists!"
#
if os.path.isdir(backup_file_path):
    raise "Backup file already exists!"
#

cmd = "/usr/local/bin/svnadmin hotcopy --clean-logs " + repository_path + " " + backup_dir_path
ret = os.system(cmd)
if ret != 0:
    raise "command failed '" + cmd + "'"
#

if not os.path.isdir(backup_dir_path):
    raise "Backup path not created!"
#

cmd = "/bin/tar -C " + backup_dir_path + " -cvvf " + backup_file_path + " ."
ret = os.system(cmd)
if ret != 0:
    raise "command failed '" + cmd + "'"
#

if not os.path.isfile(backup_file_path):
    raise "Backup file not created!"
#

statres = os.stat(backup_file_path)
file_length = statres.st_size

f = file(backup_file_path, "rb")
if not f:
    raise "Can't open backup file!"
#

print "Content-Type: application/octet-stream"
print "Content-Length: " + str(file_length)
print
sys.stdout.flush()

while True:
    block = f.read(16384)
    if len(block) == 0:
        break
    #
    os.write(1, block)
#

ret = os.system("rm -rf " + backup_dir_path + " " + backup_file_path)
if not f:
    raise "Failed to clean up"
#

os._exit(0)
