# Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights
# reserved. Use of this source code is governed by a BSD-style license that
# can be found in the LICENSE file.

import pickle
from optparse import OptionParser
import os
import sys
from file_util import *
from patch_util import *


# cannot be loaded as a module
if __name__ != "__main__":
    sys.stderr.write('This file cannot be loaded as a module!')
    sys.exit()
    

# parse command-line options
disc = """
This utility applies patch files.
"""

parser = OptionParser(description=disc)
parser.add_option('--patch-config', dest='patchconfig', metavar='DIR',
                  help='patch configuration file')
(options, args) = parser.parse_args()

# the patchconfig option is required
if options.patchconfig is None:
    parser.print_help(sys.stdout)
    sys.exit()

# normalize the patch directory value
patchdir = os.path.dirname(os.path.abspath(options.patchconfig)).replace('\\', '/')
if patchdir[-1] != '/':
    patchdir += '/'

# check if the patching should be skipped
if os.path.isfile(patchdir + 'NOPATCH'):
    nopatch = True
    sys.stdout.write('NOPATCH exists -- files have not been patched.\n')
else:
    nopatch = False
    # locate the patch configuration file
    if not os.path.isfile(options.patchconfig):
        sys.stderr.write('File '+options.patchconfig+' does not exist.\n')
        sys.exit()
    
    scope = {}
    execfile(options.patchconfig, scope)
    patches = scope["patches"]
    
    for patch in patches:
        file = patchdir+'patches/'+patch['name']+'.patch'
        dopatch = True

        if 'condition' in patch:
          # Check that the environment variable is set.
          if patch['condition'] not in os.environ:
            sys.stderr.write('Skipping patch file '+file+'\n')
            dopatch = False

        if dopatch:
          if not os.path.isfile(file):
              sys.stderr.write('Patch file '+file+' does not exist.\n')
          else:
              sys.stderr.write('Reading patch file '+file+'\n')
              dir = patch['path']
              patchObj = from_file(file)
              patchObj.apply(dir)
              if 'note' in patch:
                  separator = '-' * 79 + '\n'
                  sys.stderr.write(separator)
                  sys.stderr.write('NOTE: '+patch['note']+'\n')
                  sys.stderr.write(separator)

# read the current include file, if any
incfile = patchdir + 'patch_state.h'
if nopatch:
    incnew = """// This file is generated by the patch tool and should not be edited manually.
#ifndef _PATCH_STATE_H
#define _PATCH_STATE_H
// No patches have been applied to the Chromium/WebKit source base.
#define CEF_PATCHES_APPLIED    0
#endif // _PATCH_STATE_H
"""
else:
    incnew = """// This file is generated by the patch tool and should not be edited manually.
#ifndef _PATCH_STATE_H
#define _PATCH_STATE_H
// Patches have been applied to the Chromium/WebKit source base.
#define CEF_PATCHES_APPLIED    1
#endif // _PATCH_STATE_H
"""

inccur = ''
if os.path.isfile(incfile):
    inccur = read_file(incfile)
    
if inccur != incnew:
    sys.stdout.write('Writing file '+incfile+'.\n')
    write_file(incfile, incnew)