#!/usr/bin/perl

use File::stat;
use Config::Simple '-strict';
use File::Basename;
use Getopt::Long;

use strict;
use warnings;

my $config_file;
my $machine;
my $update;
my $show_local_modified_files;
my $show_conflict_files;

my $result = GetOptions(
    "config|c=s" => \$config_file,
    "machine|m=s" => \$machine,
    "update|u" => \$update,
    "local-modified-files|l" => \$show_local_modified_files,
    "conflict-files|f" => \$show_conflict_files,
);

unless ($result) {
    print "Usage: $0 --config ini-file --machine fedora9 [--local-modified-files|--conflict-files] [--update]\n";
    die;
}

die "`remote' can not be used as machine name\n" if $machine eq "remote";
if (defined $show_local_modified_files
	and defined $show_conflict_files) {
    die "--local-modified-files and --conflict-files are not allowed to use simultaneously\n";
}

my $config = Config::Simple->new(syntax=>'ini');
$config->read($config_file) if -e $config_file;

my @local_modified_files;
my @conflict_files;

for my $file (@ARGV) {
    my $mtime = stat($file)->mtime;
    my $filename = basename $file;
    my $key = "$machine.$filename";
    my $last_mtime = $config->param($key);
    if (! defined $last_mtime or $mtime > $last_mtime) {
	push @local_modified_files, $file;
    }
    elsif ($mtime < $last_mtime) {
	warn "something wrong on $file.\n";
    }
    $config->param($key, $mtime) if defined $update;

    my $remote_key = "remote.$filename";
    my $remote_last_mtime = $config->param($remote_key);
    # since last syncing, both remote and local files change.
    if (defined $remote_last_mtime and $remote_last_mtime > $last_mtime
	    and defined $last_mtime and $mtime > $last_mtime) {
	push @conflict_files, $file;
    }
    $config->param($remote_key, $mtime) if defined $update;
}

$config->write($config_file) if defined $update;

print "@local_modified_files\n" if defined $show_local_modified_files;
print "@conflict_files\n" if defined $show_conflict_files;
