#! perl
# Copyright (C) 2007-2014, Parrot Foundation.

=head1 NAME

tools/build/fixup_gen_file.pl - mark a generated file as generated

=head1 SYNOPSIS

    % perl tools/build/fixup_gen_file.pl <options> <generated_file> <dest_file>

=head1 DESCRIPTION

This script adds special headers and footers to files generated by tools
outside of Parrot's normal build process.  This is so that people do not
accidentally modify these files.

=head1 OPTIONS

=over 4

=item noheaderizer

This option adds directives to C<dest_file> that instruct headerizer to ignore
the file.

=back

=cut

use strict;
use warnings;

use Getopt::Long;
use lib 'lib';
use Parrot::BuildUtil;

GetOptions( \my %opts, "noheaderizer", ) or die "error processing options";

my ( $gen_file, $source ) = @ARGV;
my $contents =
    -e $gen_file
    ? Parrot::BuildUtil::slurp_file($gen_file)
    : die "Cannot find '$gen_file': $!\n";

# fix slashies in source filename for display in header
$source =~ s/\\/\//g;

my $header = Parrot::BuildUtil::generated_file_header( $source, 'c' );

my $noheaderizer = <<END_NOHEADERIZER;
/* HEADERIZER HFILE: none */
/* HEADERIZER STOP */
END_NOHEADERIZER

# if the generated file exists, make sure the header isn't there already
open( my ($gen_fh), '<', $gen_file )
    or die "Cannot read '$gen_file': $!\n";
read $gen_fh, my $block, length $header;
exit if $block eq $header;

open( my $dest_fh, '>', $gen_file )
    or die "Cannot write to '$gen_file': $!\n";

print {$dest_fh} $header, ( exists $opts{noheaderizer} ? $noheaderizer : () ), $contents;

close $dest_fh;

# Local Variables:
#   mode: cperl
#   cperl-indent-level: 4
#   fill-column: 100
# End:
# vim: expandtab shiftwidth=4:
