+#!/usr/bin/python
+# Database script runner
+# Copyright 2007 Svenne Krap
+# License ASL 2.0
+#
+# Usage:
+#   - ensure you have a file named DATABASE that contains the name of your target db 
+#       ie "echo project_test > DATABASE"
+#   - remember to exclude it from your SCM
+#       ie. "echo DATABASE >> .gitignore" (if using git)
+#   - if you want to run it in normal mode you need a file called PRODMODE
+#       ie. "touch PRODMODE"
+#
+#   Files needs to be called nnnn_XXXXXXX.sql (or use sqledit)
+#       i.e. any amount of digits (0-9) followed by one underscore followed by some
+#       string followed by ".sql"
+#
+#   Run the command as rundb nnnn 
+#   
+import sys
+import os
+import time
+
+PAGER = os.environ.get('PAGER', 'more')
+argc = len(sys.argv)
+
+try:
+       db = open("DATABASE","r").read().strip()
+except:
+       print "Need database name in file DATABASE"
+       sys.exit(1)
+
+files = os.listdir('.')
+files.sort()
+mode = "unknown"
+if 'DIAGMODE' in files: mode = "diag"
+if 'PRODMODE' in files: mode = "prod"
+if mode=="unknown":
+       print "Unable to determine DIAGMODE or PRODMODE. Please touch appropriate file in run-dir"
+       sys.exit(0);
+
+try:
+       os.chdir("output")
+except:
+       os.mkdir("output")
+       os.chdir("output")
+os.chdir("..")
+
+
+
+rt = time.localtime()
+logfile = "output/run_" + time.strftime("%Y-%m-%d-%H-%M-%S",rt)  +  ".log"
+
+
+if argc < 2 or argc > 3: 
+       print "Syntax: rundb.py <from> [exclude_tags]"
+       print
+       print "dbname = name of database"
+       print "from = integer of first command"
+       print "exclude_tags = comma separated list of strings in filename to exclude"
+       if argc == 1:
+               print "Log is written to " + logfile
+               os.system("psql -d %s -e -L %s" % (db,logfile) )
+               print "Log was written to " + logfile
+               sys.exit(0)
+       sys.exit(1)
+
+def db_run_file(db,f,logfile):
+       os.system("echo \"###RESULT### %s\" >>%s 2>&1" % (f,logfile))
+       os.system("psql --single-transaction -d %s -f %s >>%s 2>&1" % (db,f,logfile) )
+       os.system("echo \"###RUN### %s\" >>%s 2>&1" % (f,logfile))
+       os.system("cat %s  >>%s 2>&1" % (f,logfile) )
+
+if argc >= 3:
+       exclude_tags = sys.argv[2].strip().split(",")
+else:
+       exclude_tags = []
+
+if mode=='prod':
+       run_from = int(sys.argv[1])
+       for f in files:
+               good = True
+               if not f.endswith(".sql"): continue
+               pos = f.find("_")
+               if pos == -1: continue
+               first = f[:pos]
+               try:
+                       num = int(first)
+               except:
+                       num = int(first[:-1])
+               if num < run_from: continue
+               for x in exclude_tags:
+                       if not f.find(x) == -1: 
+                               good = False
+                               break
+               if good == False: continue
+               db_run_file(db,f,logfile)
+elif mode=='diag': 
+       filename = sys.argv[1] 
+       if os.path.exists(filename) and os.path.isfile(filename):
+               db_run_file(db,filename,logfile)
+
+if os.path.exists(logfile):
+       os.system('%s %s' % (PAGER, logfile))