#!/usr/bin/python
"""Doesn an svnupdate while running any update scripts that might be available for specific versions"""

import urllib2,os,glob

try:
    have_subprocess=1
    import subprocess
except:
    have_subprocess=0
import fcntl,sys

#Make sure we are the only copy running
lockfilename="/var/run/upab.pid";
try:
    lockfile=open(lockfilename,"w+")
    fcntl.flock(lockfile,fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
    print "Locked: Another update is busy running, holding /var/run/upab.pid"
    sys.exit(0)  # everything is fine - relax!
lockfile.seek(0)
lockfile.write("%s\n" % os.getpid())

def runupdates(start,finish):
    """Run any available shell scripts from the afribin update list"""
    rundir="/root/build"#We will run our scripts from here
    #Using roots home directory eliminates any permission issues or noexec flags on /tmp

    start=start+1
    print "New start: ",start
    print "Finish",finish
    if finish < start: return False

    try: os.mkdir(rundir) 
    except: pass

    # 2008/11/20  Andrew was here: svn only updates is now the thing
    #baseshellurl="https://svn.afrihost.com/afribin_upgrades/"
    unlinklist=[]
    for i in range(start,finish+1):
	# Maybe there's a svn update.d file ...
        updatelist = glob.glob("update.d/"+str(i)+"_*")
	# IFF there are no updates matchin update.d/999_*, then download from https://svn.afrihost.com/afribin_upgrades/999.txt 
	#if updatelist == [] :
	#   shellurl=baseshellurl+str(i)+".txt" 
        #   print "Downloading update script '%s.sh' " % (i)
        #   try: fh=urllib2.urlopen(shellurl)
        #   except:
        #      #print "Could not open",shellurl
        #      continue
        #   fname = os.path.join(rundir, "%s.sh" % (i));
        #   f=open(fname,"w")
        #   f.write(fh.read())
        #   fh.close()
        #   f.close()
        #   updatelist = [ fname ]
        #   unlinklist = updatelist
	# Run each script
	for fname in updatelist:
           print "Running "+fname
	   os.chmod(fname,0700)
           #Execute the shell command with the repository directory as an argument
           if have_subprocess:
               process = subprocess.Popen(fname,shell=False,close_fds=True)
               status = os.waitpid(process.pid, 0)
           else:
                status=os.system(fname)
	# We may want to clean up the update.d directories too ... but it would
	# be better if we did that with svn, I reckon.
	for fname in unlinklist:
           os.unlink(fname)
        
def getSVNRevision():
    """Finds the current revision id for the current directory"""
    f=os.popen("svn info","r")
    revision=-1
    for line in f:
        if line.find("Revision:")==0:
            revision=line[len("Revision:"):].strip()
            try:revision=int(revision)
            except: revision=-2
            break
    f.close()
    return revision

def activeUpdate():
    """Does an svn update and then downloads and executes and required scripts"""
    startversion=getSVNRevision()
   # paulo adding some form of auth so the world can't just download our stuff
    #rc = os.system("svn info >/dev/null && yes tf 2>/dev/null |svn up")
    rc = os.system("svn info >/dev/null && yes tf 2>/dev/null | svn --username elp --password 'Zzbao.Otetq2' up")
    finishversion=getSVNRevision()
    # print "From revision %d to %d" % (startversion , finishversion)
    if finishversion==startversion:
        return rc
    runupdates(startversion,finishversion) 
    return rc  # if fail, return fail

rc = activeUpdate()
os.system("/usr/local/afribin/sshkeysupdate")
lockfile.close()
if os.path.exists(lockfilename): os.unlink(lockfilename)
if rc: rc=1
sys.exit(rc)
