#! /usr/bin/env python

# This file is part of release-path
#
#Copyright (c) 2012 Wireless Generation, Inc.
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.


from argparse import ArgumentParser
from git import Repo
import sys
from release_path import (
    verify_submodule_branch_structure, fast_forward_deep_merge,
    no_ff_deep_merge, deep_merge
)


def argparser():
    parser = ArgumentParser()
    parser.add_argument('--no-fetch', action='store_true')
    parser.add_argument('from_branch')
    parser.add_argument('to_branch')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--ff-only', action='store_true')
    group.add_argument('--no-ff', action='store_true')
    return parser


def main():
    args = argparser().parse_args()
    repo = Repo()

    if args.no_fetch:
        print "--no-fetch flag found; skipping git fetch"
    else:
        repo.git.fetch()

    # Verify that the submodules have the correct branch structure
    for branch in [args.from_branch, args.to_branch]:
        verify_submodule_branch_structure(repo, branch, not args.no_fetch)
    
    if args.ff_only:
        fast_forward_deep_merge(repo, args.from_branch, args.to_branch)
    elif args.no_ff:
        no_ff_deep_merge(repo, args.from_branch, args.to_branch)
    else:
        deep_merge(repo, args.from_branch, args.to_branch)


if __name__ == "__main__":
    sys.exit(main())
