#! /usr/bin/env python
# Migrate from an OpenRPG 1.7.8-rc4-dvN release to FlexiRPG

import sys
import os
import errno
import distutils.core
import distutils.dir_util as dir_util
import distutils.file_util as file_util
import xml.dom.minidom

def done(code):
    raw_input("Press Enter to continue.")
    exit(code)

#
# Path to user files.
#
# Windows:
#    %APPDATA%\OpenRPG\ = X:\Documents\<user>\Application Data\FlexiRPG\
#
# Linux:
#   $HOME/.flexirpg/ = /home/<user>/.flexirpg/
#
if 'APPDATA' in os.environ:
    openrpg_dir = os.path.join(os.environ['APPDATA'], "OpenRPG")
    flexirpg_dir = os.path.join(os.environ['APPDATA'], "FlexiRPG")
elif 'HOME' in os.environ:
    openrpg_dir = os.path.join(os.environ['HOME'], ".openrpg")
    flexirpg_dir = os.path.join(os.environ['HOME'], ".flexirpg")
else:
    # Neither Windows nor Linux?
    print "Can only migrate Windows or Linux installations."
    done(1)

try:
    os.stat(flexirpg_dir)
    print "OpenRPG files already migrated."
    done(0)
except OSError, e:
    if e.errno != errno.ENOENT:
        print "Error: %s" % (e.message)
        done(1)

try:
    dir_util.copy_tree(openrpg_dir, flexirpg_dir, preserve_mode=1, preserve_times=1, preserve_symlinks=1)
except distutils.core.DistutilsFileError, e:
    print "Error copying '%s' -> '%s': %s" % (openrpg_dir, flexirpg_dir, e.message)
    done(1)

settings_xml = os.path.join(flexirpg_dir, "settings.xml")
try:
    settings_doc = xml.dom.minidom.parse(settings_xml)
except Exception, e:
    print "Invalid settings file '%s': %s" % (settings_xml, e.message)
    done(1)

try:
    gametree_node = settings_doc.getElementsByTagName("gametree")[0]
    old_gametree = gametree_node.getAttribute("value")
except:
    print "'%s' doesn't contain OpenRPG settings" % (settings_xml)
    done(1)

new_gametree = os.path.join(flexirpg_dir, "tree.xml")

try:
    file_util.copy_file(old_gametree, new_gametree, preserve_mode=1, preserve_times=1)
except Exception, e:
    print "Error copying '%s' -> '%s': %s" % (old_gametree, new_gametree, e.message)
    done(1)

gametree_node.setAttribute("value", new_gametree)

try:
    f = open(settings_xml, "w")
    f.write(settings_doc.toxml())
    f.close()
except Exception, e:
    "Error updating settings: %s" % (e.message)
    done(1)

print "Settings successfully migrated."
done(0)
