#!/usr/bin/perl -w

use strict;

open(MODULES, "<modules") || die;
while (<MODULES>) {
    chomp;
    my $dir = $_;
    my $file = "$dir/CMakeLists.txt";
    my $cmr;
    my $first_real_line;
    my $bad_first_line = 1; # assume the worst
    my $version;
    open(my $F, "$file") || die "$file";
    while (<$F>) {
        next if (/^#/);
        next if (/^\s*$/);
        #next if (/^project/i);
        #print "$file: $_";
        if (/^\s*cmake_minimum_required/i) {
            $cmr = $_;
            if (($version) = /cmake_minimum_required\s*\(\s*VERSION\s+([0-9\.]+)/i) {
            } else {
                die "$file: parse error on $_";
            }
            $bad_first_line = 0 unless defined $first_real_line;
        }
        if (!defined $first_real_line) {
            $first_real_line = $_;
        }
    }
    close $F;
    next if ($version eq "2.8.9");
    if (!defined $cmr) {
        print "$file is missing cmake_minimum_required\n";
    } elsif ($bad_first_line) {
        print "$file: contains cmake_minimum_required but not as the first real line\n";
    } else {
        print "$file requires $version, changing that to 2.8.9\n";
    }
    open(my $FILE, "$file") || die "$file";
    my @l = map {
        $_ .= "\n" if eof($FILE) && !/\n/;    # always terminate with a newline
        $_ = "" if (defined $first_real_line && /^\s*cmake_minimum_required/i);
        $_;
    } <$FILE>;

    print STDERR "Saving $file\n";
    open (my $OUT, ">", $file);
    print $OUT "cmake_minimum_required(VERSION 2.8.9)\n";
    print $OUT @l;
    close ($FILE);
}
close MODULES;

