#!/usr/bin/env python

# $Id: upgrade 18381 2009-06-11 17:25:01Z davea $

'''
Usage: upgrade [options] project_name
Options:
  --project_root    default: HOME/projects/
  --srcdir          default: current directory

Copy source/build files to a project tree,
overwriting what's already there.
Run it in the source directory (tools/upgrade).

'''

import boinc_path_config
from Boinc import boinc_project_path, tools
from Boinc.setup_project import *
import os, getopt

def usage():
    print "Usage: upgrade [--project_root] [--web_only] [--srcdir DIR] project_name"
    raise SystemExit

def syntax_error(str):
    raise SystemExit('%s; See "%s --help" for help\n' % (str, sys.argv[0]))

try:
    opts, args = getopt.getopt(sys.argv[1:], '', ['help', 'project_root=', 'web_only', 'srcdir='])
except getopt.GetoptError, e:
    syntax_error(e)

home = os.path.expanduser('~')

options.project_root = os.path.join(home, 'projects')
options.web_only = False
options.srcdir = None

for o,a in opts:
    if o == '--help':   usage()
    elif o == '--project_root': options.project_root = a
    elif o == '--web_only': options.web_only = True
    elif o == '--srcdir': options.srcdir = a
    else:
        raise SystemExit('internal error o=%s'%o)

if len(args) == 1:
    project_shortname = args[0]
else:
    syntax_error('No project name')

if not options.srcdir:
    for dir in ('.', '..'):
        if os.path.exists(os.path.join(dir, 'html', 'project.sample', 'project.inc')):
            options.srcdir = dir
    if not options.srcdir:
        syntax_error('Not running in the source directory and --srcdir was not specified')

INSTALL_DIR = os.path.join(options.project_root, project_shortname)

if not tools.query_noyes("Overwrite files in "+INSTALL_DIR):
    raise SystemExit

if not options.web_only:
    if os.system(os.path.join(INSTALL_DIR,'bin/stop')):
        raise SystemExit("Couldn't stop project!")

print "Upgrading files... "

options.install_method = 'copy'
init()
install_boinc_files(INSTALL_DIR, options.web_only)

print "Upgrading files... done"

svn_version_file = INSTALL_DIR+'/local.revision'
try:
    os.system('/bin/sh -c /usr/bin/svnversion > '+svn_version_file)
except:
    print '''Couldn't find svnversion'''

try:
    os.system('cd '+INSTALL_DIR+'/html/ops; ./update_translations.php -d 1')
except:
    print '''Couldn't install translation files'''

os.system('cd '+INSTALL_DIR+'/html/ops; ./upgrade_db.php')

if not options.web_only:
    print "Run `bin/start' to restart the project."
