#!/usr/bin/perl -w
# Utility script for tidying Zymonic
# Should be run before all commits

use File::Find;
use Perl::Tidy;
use Cwd;
use strict;

my $quiet  = 0;
my $backup = 0;

# Check the perl tidy RC file.
my $perltidyrc = getcwd . '/scripts/perltidyrc.zymonic';
die "Cannot find scripts/perltidyrc.zymonic"
  unless ( -f $perltidyrc );

# Find all pm, pl, xml, xsl and xsd files
find( { wanted => \&do_clean }, getcwd );

# callback to do the tidying.
sub do_clean
{
    my $file        = $File::Find::name;
    my $destination = $file . ".tidied";

    # Skip SVN resources
    return if $file =~ /\.svn/;
    return if $file =~ /\.backup/;

    my $ss = `svn status $file`;
    return unless $ss;

    if ( $file =~ /\.xml|\.xsd/ )
    {
        print "\n--- Cleaning XML file: " . $file . " ---\n" unless $quiet;
        `cp $file $file.backup` if $backup;

        my $clean = `tidy -i2 -xml $file 2>/dev/null`;

        open( FH, ">$destination" );
        foreach my $line ( split( /\n/, $clean ) )
        {
            if ( $line =~ /\s*<!\-\-/ )
            {
                print FH "\n";
            }
            print FH $line . "\n";
        }
        close(FH);

    }
    elsif ( $file =~ /\.pm|\.pl|\.PL|\.t$/ )
    {
        print "\n--- Cleaning Perl file: " . $file . " ---\n" unless $quiet;
        `cp $file $file.backup` if $backup;
        Perl::Tidy::perltidy(
            source      => $file,
            destination => $destination,
            perltidyrc  => $perltidyrc,
        );

    }
    else
    {
        return;
    }

    my $differences = `diff $file $destination`;
    if ($differences)
    {
        print $differences unless $quiet;
        print "\n";

        unlink($file);
        rename( $destination, $file );

    }
    else
    {
        unlink($destination);
    }

    print "--- Done $file ---\n" unless $quiet;
}
