#!/opt/csw/bin/python

# This is written by Niclas Sodergard
# Public domain, feel free to use it as you wish
# There is no warranty whatsoever.
# There is no guarantee that this will actually work.

import commands
import MySQLdb
import sys
import time

if len(sys.argv) != 2:
	print "Usage: ./backup_mysql.py <configurationfile>"
	print
	print "The configuration file needs to contain the following lines:"
	print
	print "\tuser=<username>"
	print "\tpassword=<password>"
	print "\thostname=<hostname or IP of the MySQL server>"
	print "\tfilesystem=<zfs filesystem to snapshot>"
	sys.exit(1)

config = {}

try:
	f = open(sys.argv[1], "r")
except IOError:
	print "Can't open file %s." % sys.argv[1]
	sys.exit(1)
	
#
# read and parse the configuration file
#
for line in f.readlines():
	line = line.lstrip().rstrip()
	if (len(line) == 0) or (line[0] == "#"):
		continue

	if line.find("=") == -1:
		print "Line must be of the form 'key=value'"
		sys.exit(1)

	key, value = line.split("=")
	config[key] = value

f.close()

#
# make sure we have all the necessary configuration information
#
for key in ["user", "password", "hostname", "filesystem"]:
	if not config.has_key(key):
		print "Configuration file didn't contain '%s' key." % key
		sys.exit(1)

try:
	db = MySQLdb.connect(host = config["hostname"], user = config["user"], passwd = config["password"])
except MySQLdb.OperationalError:
	print "Can't connect to %s." % config["hostname"]
	sys.exit(1)

cursor = db.cursor()

timestamp = time.strftime("%Y%m%d%H%M%S")

# lock all tables in the database
cursor.execute("FLUSH TABLES WITH READ LOCK;")

print "Creating snapshot %s@%s" % (config["filesystem"], timestamp)
status, output = commands.getstatusoutput("/usr/sbin/zfs snapshot %s@%s" % (config["filesystem"], timestamp))

if status != 0:
	print output

# and we are free to proceed
cursor.execute("UNLOCK TABLES;")
