#!/usr/bin/perl
#
# Copyright (c) 2022 Adrian Schroeter, Novell Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# 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 (see the file COPYING); if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
#
################################################################
#
# Initialize a git repository to be used with Open Build Service (OBS)
#

use Cwd;
use Config::IniFiles;

my $workdir = getcwd;
$workdir = shift @ARGV if @ARGV == 1;

# set merge handler in .git/config
my $config_file = "$workdir/.git/config";
my $cfg = Config::IniFiles->new( -file => $config_file ) || die("ERROR: No git config found, you may want to run 'git init' first");

my $section='merge "merge-changes"';
unless ($cfg->exists($section, 'driver')) {
  $cfg->AddSection($section);
  $cfg->newval($section, 'name', 'Merging changes files by sorting of date');
  $cfg->newval($section, 'driver', '/usr/lib/obs/helper/bs_mergechanges %O %B %A');
  $cfg->WriteConfig($config_file) || die("ERROR: Write $config_file failed!\n");
}

# set .gitattributes file
my $attrib_file = "$workdir/.gitattributes";
my $gitattributes='';
if (-e $attrib_file) {
  open(FH, '<', $attrib_file) || die "unable to read .gitattributes";
  {
    local $/;
    $gitattributes = <FH>;
  }
  close(FH);
}
unless ($gitattributes =~ m/^*.changes merge=merge-changes/) {
  $gitattributes .= "*.changes merge=merge-changes\n" unless $gitattributes =~ m/^*.changes merge=merge-changes/;
  open(FH, '>', $attrib_file) or die $!;
  print FH $gitattributes;
  close(FH);
}


