##############################################################################
#
# Copyright (c) 2012 Vifib SARL and Contributors. All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly adviced to contract a Free Software
# Service Company
#
# 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 3
# 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 os

from subprocess import check_call

GIT_DEFAULT_REMOTE_NAME = 'origin'
GIT_DEFAULT_BRANCH_NAME = 'master'
TRUE_VALUES = ['y', 'yes', '1', 'true']

class Recipe(object):
  """Clone a git repository."""

  def __init__(self, buildout, name, options):
    self.url = options.get('url')
    self.branch = options.get('branch', GIT_DEFAULT_BRANCH_NAME)
    self.revision = options.get('revision')
    self.git_command = options.get('git-command', 'git')
    self.location = options.get('location',
        os.path.join(buildout['buildout']['parts-directory'], name))
    if options.get('develop') in TRUE_VALUES:
      self.develop = True

    if not self.url:
      raise ValueError('url parameter is mandatory.')

    if self.revision and self.branch != GIT_DEFAULT_BRANCH_NAME:
      # revision and branch options are incompatible
      raise ValueError('revision and branch parameters are set but are '
          'incompatible. Please specify only one of them.')


  def gitReset(self, revision=None):
    """Operates git reset on the repository."""
    command = [self.git_command, 'reset', '--hard']
    if revision:
      command.append(revision)
    check_call(command, cwd=self.location)


  def install(self):
    """
    Do a git clone.
    If branch is specified, checkout to it.
    If revision is specified, reset to it.
    """
    if not os.path.exists(self.location):
      git_clone_command = [self.git_command, 'clone',
                  self.url,
                  self.location]
      if self.branch:
        git_clone_command.extend(['--branch', self.branch])
      check_call(git_clone_command)

    if self.revision:
      self.gitReset(self.revision)

    return [self.location]


  def update(self):
    """
    Do a git fetch.
    If user doesn't develop, reset to remote revision (or branch if revision is
    not specified.)
    """
    check_call([self.git_command, 'fetch', '--all'], cwd=self.location)

    # If develop parameter is set, don't reset/update.
    # Otherwise, reset --hard
    if not self.develop:
      if self.revision:
        self.gitReset(self.revision)
      else:
        self.gitReset('%s/%s' % (
            GIT_DEFAULT_REMOTE_NAME, self.branch))