from fabric.api import task, run, local, env, cd, put, prefix, sudo
from fabric.colors import green
from fabric.contrib.project import rsync_project
from fabric.contrib.files import exists, upload_template
from fabric.context_managers import settings 
from mercurial import commands, ui, hg, cmdutil
import imp
import os, os.path
import shutil
import sys

import config

def get_export_path(version):
    base_path = os.path.join(env.base_export_path,env.export_prefix).lstrip("/")
    return os.path.expanduser(base_path) + "_%s" % (str(version))

def clean_export_folder(path):
    print("Removing %s" % path)
    if os.path.isdir(path):
        shutil.rmtree(path, ignore_errors=True)

def do_export_version(path, version):
    print("Export version %s"%str(version))
    
    #hgui = ui.ui() 
    #repo = hg.repository(hgui, cmdutil.findrepo(os.getcwd()))
    #commands.archive(hgui, repo, path, rev=str(version))
    
    local("hg archive -r \'%s\' \"%s\"" % (str(version),path))
    print("Export version %s done"%str(version))
    
def rsync_export(path, remotepath, filters):
    print("Rsync %s to %s",(path,remotepath))
    
    if filters:
        filter_option_str = " ".join(["--filter \"%s\"" % (f) for f in filters])
    else:
        filter_option_str =""
    
    run("mkdir -p \"%s\"" % remotepath)
    rsync_project(remotepath, local_dir=path, extra_opts=filter_option_str, delete=True)
    print("Rsync %s to %s done",(path,remotepath))
    
def clean_rsync_folder(remotepath):
    print("clean rsync folder %s" % remotepath)
    run("rm -fr \"%s\"" % remotepath)    

        
def export_version(version):
    print("export version %s" % str(version))
    
    export_path = get_export_path(version)
    
    clean_export_folder(export_path)
    do_export_version(export_path,version)
    
    return export_path

def do_sync_web(version, export_path):
    print("do_sync_web with version %s and path %s" % (version,export_path))
    web_path = os.path.join(export_path,"front_idill/") 
    rsync_export(web_path, env.remote_web_path, env.web_rsync_filters)    
    
def relaunch_server():
    print("Relaunch server")
    sudo(env.web_relaunch_cmd, shell=False)

@task
def sync_web(version):
    print(green("sync web with version %s" % version))
    export_path = export_version(version)
    do_sync_web(version, export_path)
    clean_export_folder(export_path)
    relaunch_server()
