#!/usr/bin/perl -w

use strict;
use warnings;
use Pod::Usage;
use Gear::Rules;
use Getopt::Long;

my $help;
my $verbose_default=1;
my $verbose=$verbose_default;
my $force;

my $options_result = 
    GetOptions (
	"h|help"   => \$help,
	"verbose+"  => \$verbose,
	"quiet"  => sub {$verbose=0},
	"f|force"   => \$force,
    );

sub exit_usage {
    #exec "pod2usage --exit=0 $0";
    pod2usage({ #-message => "the options below are package-specific:" ,
	-exitval => 0  ,
	-verbose => $verbose ? $verbose - $verbose_default : 0,
	#-output  => $filehandle
	      } );
}

if ($help) {
    &exit_usage();
}



my $rules=Gear::Rules->new();
my $branch_ref=&Gear::Git::Helper::get_git_branch_commit_hash();
my %TAG=map {$_=>1} &Gear::Git::Helper::ls_git_tags();
my %CREATED;

foreach my $rule (@{$rules->{RULES}}) {
    next if $rule->{-optional};
    my $type=$rule->type;
    next if $type eq 'copy';
    my @git_paths=$rule->git_paths();
    foreach my $git_path (@git_paths) {
	my $branchname=$git_path->{tag};
	my $branch_template=$git_path->{tag_template};
	next if $branch_template eq '.';
	next if &Gear::Rules::template_is_likely_a_tag($branch_template) or $TAG{$branchname} or $CREATED{$branchname};
	my $commit=$git_path->{'commit'};
	if (!$force and $branch_ref->{$branchname}) {
	    warn "branch $branchname already exists.\n" if $verbose;
	} elsif ($commit and $commit ne '.') {
	    run(qw/git branch/,$force ? '--force' : (),$branchname, $commit);
	    $CREATED{$branchname}=$commit;
	    print STDERR "created: $branchname\n" if $verbose;
	} else {
	    warn "can't determine commit for branch $branchname\n";
	}
    }
}

sub run {
    print STDERR "running: ", join(' ',@_),"\n" if $verbose>1;
    system(@_)==0 or die "command failed: ".join(' ',@_);
}


=head1	NAME

gear-rules-restore-branches - restore git branches saved in .gear/tags.

=head1	SYNOPSIS

B<gear-rules-restore-branches>
[B<-h>] 
[B<-f, --force>] 
[B<-v>] 
[B<-q>] 

=head1	DESCRIPTION

gear-rules-restore-branches - ALTLinux Gear

=head1	OPTIONS

=over

=item	B<-h, --help>

Display this help and exit.

=item	B<-f, --force>

Modify existing branches.

=item	B<-v, --verbose>

Increase verbosity level.

=item	B<-q, --quiet>

Quiet mode.

=back

=head1	AUTHOR

Written by Igor Vlasenko <viy@altlinux.org>.

=head1	COPYING

Copyright (c) 2010 Igor Vlasenko, ALT Linux Team.

This 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.

=cut

