#!/usr/bin/perl

# Copyright 2016 by Shlomi Fish
# This program is distributed under the MIT (X11) License:
# http://www.opensource.org/licenses/mit-license.php

use strict;
use warnings;

use File::Find;

my $buildroot = $ENV{RPM_BUILD_ROOT};
die "No build root defined" unless $buildroot;
die "Invalid build root" unless -d $buildroot;
# normalize build root
$buildroot =~ s|/$||;

my $FILTER = qr/\.desktop\z/;

# List of error messages from desktop-file-validate that are allowed.
my @IGNORED_ERRORS = (
    qr/: error: key "Exec" in group "Desktop Entry" is required if key "DBusActivatable" is not set to true in the main desktop entry group\.?\s*\z/,
);

# Check if error is allowed
sub is_ignored {
    my ($line) = @_;
    foreach my $re (@IGNORED_ERRORS)
    {
        return 1 if $line =~ $re;
    }
    return 0;
}

# Returns 1 if the file is valid, or only fails with allowed errors.
sub validate_file {
    my ($fn) = @_;

    # Fork to capture both stdout and stderr.
    my $pid = open(my $pipe, '-|');
    die "Cannot fork: $!" unless defined $pid;
    if ($pid == 0)
    {
        open(STDERR, '>&', \*STDOUT) or die "Cannot dup STDOUT: $!";
        exec('desktop-file-validate', $fn)
            or die "Cannot run desktop-file-validate on <$fn>: $!";
    }
    my @lines = <$pipe>;
    close($pipe);
    my $status = $?;

    # Exit for fully compliant files
    return 1 if $status == 0;

    # Loop aver all messages and skip recording the ignored errors.
    my @remaining;
    my $ignored = 0;
    foreach my $line (@lines)
    {
        chomp $line;
        next if $line =~ /A\s*\z/;
        if (is_ignored($line))
        {
            # Ignoring the error message.
            warn "Ignoring known error: $line\n";
            $ignored++;
            next;
        }
        push @remaining, $line;
    }

    # Record any other runtime errors.
    my @problems = grep { !/: (?:warning|hint):/ } @remaining;

    # Zero exit for any other errors but the ignored ones.
    if (!$ignored || @problems)
    {
        print STDERR "$_\n" foreach @remaining;
        return 0;
    }

    # Print ignored errors, plus possibly warnings/hints.
    print STDERR "$_\n" foreach @remaining;
    return 1;
}

sub main
{
    find(
        {
            wanted =>
            sub {
                # check files only in /usr/share/applications
                return unless $File::Find::dir eq $buildroot . '/usr/share/applications';

                my $fn = $File::Find::name;
                if ($fn =~ $FILTER)
                {
                    if (!validate_file($fn))
                    {
                        die "Validating <$fn> failed!";
                    }
                }
            },
            no_chdir => 1,
        },
        $buildroot
    );

    exit(0);
}

main(@ARGV);
