# Copyright (C) 2005, 2008 Aaron Bentley, 2006 Michael Ellerman
# <aaron@aaronbentley.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
import sys
import subprocess

import bzrlib.add

from bzrlib.plugins.bzrtools.bzrtools import open_from_url
from errors import PatchFailed, PatchInvokeError

def patch(tree, location, strip, quiet=False):
    """Apply a patch to a branch, using patch(1).  URLs may be used."""
    my_file = None
    if location is None:
        my_file = sys.stdin
    else:
        my_file = open_from_url(location)
    patches = [my_file.read()]
    return run_patch(tree.basedir, patches, strip, quiet=quiet)


def run_patch(directory, patches, strip=0, reverse=False, dry_run=False,
              quiet=False, _patch_cmd='patch', target_file=None):
    args = [_patch_cmd, '-d', directory, '-s', '-p%d' % strip, '-f']
    if quiet:
        args.append('--quiet')

    if sys.platform == "win32":
        args.append('--binary')

    if reverse:
        args.append('-R')
    if dry_run:
        if sys.platform.startswith('freebsd'):
            args.append('--check')
        else:
            args.append('--dry-run')
        stderr = subprocess.PIPE
    else:
        stderr = None
    if target_file is not None:
        args.append(target_file)

    try:
        process = subprocess.Popen(args, stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE, stderr=stderr)
    except OSError, e:
        raise PatchInvokeError(e)
    try:
        for patch in patches:
            process.stdin.write(str(patch))
        process.stdin.close()

    except IOError, e:
        raise PatchInvokeError(e, process.stderr.read())

    result = process.wait()
    if not dry_run:
        sys.stdout.write(process.stdout.read())
    if result != 0:
        raise PatchFailed()

    return result
