#!/usr/bin/env perl 

use strict;
use warnings;
use utf8;

use File::Slurp;
use C4::Context;

system("git grep -n 'C4::Context->preference' > lines_with_prefs");

my @lines  = read_file('lines_with_prefs');
my $errors = 0;

my $dbh = C4::Context->dbh;

my $case_sensitive = q{
    SELECT  COUNT(*)
    FROM    systempreferences
    WHERE   variable = ?
    LIMIT   1
};

my $case_insensitive = q{
    SELECT  COUNT(*) 
    FROM    systempreferences 
    WHERE   LOWER( variable ) = LOWER(?)
    LIMIT   1
};

foreach my $line (@lines) {
    my @prefs = $line =~ /C4::Context->preference\((\'|\")(.*?)(\'|\")\)/;

    foreach my $pref (@prefs) {
        next if $pref =~ /(\'|\")/;

        unless ( $dbh->selectrow_array( $case_sensitive, undef, $pref ) ) {
            if ( $dbh->selectrow_array( $case_insensitive, undef, $pref ) ) {
                print "ERROR: PREF='$pref' -  $line\n";
                $errors++;
            }
        }
    }
}

print "\nFound $errors errors.\n";
