use Modern::Perl;

my @files = @ARGV;

for my $f ( @files ) {
    open my $fh, '<', $f;
    my @lines = <$fh>;
    close $fh;
    my ( $has_use_koha, $has_koha_version, $has_js, $has_css );
    for my $l ( @lines ) {
        if ( $l =~ m|<link rel="stylesheet" type="text/css"| ) {
            $has_css++;
            $l =~ s|\.css"|_[% KOHA_VERSION %].css"|
                unless $l =~ m|KOHA_VERSION|;
        }
        if ( $l =~ m|<script type="text/javascript.*src="| ) {
            $has_js++;
            $l =~ s|\.js"|_[% KOHA_VERSION %].js"|
                unless $l =~ m|KOHA_VERSION|;
        }
        if ( $l =~ m|^\[% SET KOHA_VERSION| ) {
            $has_koha_version++
        }
    }
    if ( $has_css or $has_js ) {
        unless ( $has_koha_version ) {
            @lines = grep {!/\[% USE Koha %\]/} @lines;
            unshift @lines, "[% SET KOHA_VERSION = Koha.Preference('Version') %]\n"
                unless $has_koha_version;
            unshift @lines, "[% USE Koha %]\n"
                unless $has_koha_version;
        }
        say $f;
        open my $fh, '>', $f;
        print $fh join '', @lines;
        close $fh;
    }
}
