from fabric.api import *
from fabric.contrib.files import sed
import random
import string
import time

# Small function to revert db
@task
def _revert_db(repo, branch, build):
  print "===> Dropping all tables"
  run("if [ -f ~jenkins/dbbackups/%s_%s_prior_to_%s.sql.gz ]; then drush -y @%s_%s sql-drop" % (repo, branch, build, repo, branch))
  print "===> Waiting 5 seconds to let MySQL internals catch up"
  time.sleep(5)
  print "===> Restoring the database from backup"
  run("zcat ~jenkins/dbbackups/%s_%s_prior_to_%s.sql.gz | drush @%s_%s sql-cli; fi" % (repo, branch, build, repo, branch))

# Function to revert settings.php change for when a build fails and database is reverted
@task
def _revert_settings(repo, branch, build):
  with settings(warn_only=True):
    settings_file = "/var/www/config/%s_%s.settings.inc" % (repo, branch)
    stable_build = run("readlink /var/www/live.%s.%s" % (repo, branch))
    replace_string = "/var/www/.*\.settings\.php"
    replace_with = "%s/www/sites/default/%s.settings.php" % (stable_build, branch)
    sed(settings_file, replace_string, replace_with, limit='', use_sudo=True, backup='', flags="i", shell=True)
    print "===> Reverted settings.php"


@@ -295,16 +295,20 @@
 sql-drop
+; fi
 %22 %25 (rep
@@ -478,16 +478,76 @@
 %0A  run(%22
+if %5B -f ~jenkins/dbbackups/%25s_%25s_prior_to_%25s.sql.gz %5D; then 
 zcat ~je
@@ -636,32 +636,53 @@
 ch, build, repo,
+ branch, build, repo,
  branch))%0A%0A# Fun

Fix the database revert steps