#!/usr/bin/env perl
use 5.014;
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
use JSON::PP ();
use Spreadsheet::Security::CWE1236;

our $VERSION = '1.00';

my ($opt_json, $opt_sanitize, $opt_xlsx, $opt_delim, $opt_help, $opt_ver);
$opt_delim = ',';

GetOptions(
    'json'           => \$opt_json,
    'sanitize-out=s' => \$opt_sanitize,
    'xlsx'           => \$opt_xlsx,
    'delimiter=s'    => \$opt_delim,
    'help|h'         => \$opt_help,
    'version|v'      => \$opt_ver,
) or die "Usage: cwe1236-audit [--json] [--xlsx] [--sanitize-out SAFE.csv] <input_file>\n";

if ($opt_ver) {
    print "cwe1236-audit v$VERSION (Spreadsheet::Security::CWE1236)\n";
    exit 0;
}

if ($opt_help || !@ARGV) {
    print <<"USAGE";
Usage: cwe1236-audit [OPTIONS] <file.csv | file.xlsx>

Options:
  --json               Emit audit report as structured JSON
  --xlsx               Audit binary ECMA-376 (.xlsx / .xlsm) archive for VBA, DDE & external links
  --sanitize-out <f>   Write CWE-1236 neutralized RFC 4180 CSV to <f>
  --delimiter <char>   CSV field delimiter (default: ',')
  --version, -v        Print version
  --help, -h           Show this help message
USAGE
    exit($opt_help ? 0 : 1);
}

my $input = shift @ARGV;
my $guard = Spreadsheet::Security::CWE1236->new(delimiter => $opt_delim);

if ($opt_xlsx || $input =~ /\.(?:xlsx|xlsm|xltx)$/i) {
    my $res = $guard->audit_ooxml_file($input);
    if ($opt_json) {
        print JSON::PP->new->utf8->canonical->pretty->encode($res);
    }
    else {
        printf "OOXML Archive: %s (%d ZIP entries) | Risk: %s\n",
            $input, $res->{archive_entries}, $res->{overall_risk};
        printf "VBA Macros: %s | XL4 Macros: %s | Hidden Sheets: %d | External Links: %d\n",
            ($res->{has_vba_macros} ? 'YES' : 'NO'),
            ($res->{has_xl4_macros} ? 'YES' : 'NO'),
            scalar(@{ $res->{hidden_sheets} }),
            scalar(@{ $res->{external_targets} });
    }
    exit 0;
}

open my $fh, '<:raw', $input or die "Cannot read '$input': $!\n";
local $/;
my $raw = <$fh>;
close $fh;

if (defined $opt_sanitize) {
    my $safe = $guard->sanitize_csv_string($raw);
    open my $out, '>:raw', $opt_sanitize or die "Cannot write '$opt_sanitize': $!\n";
    print {$out} $safe;
    close $out;
    printf "Wrote sanitized RFC 4180 CSV (%d bytes) to %s\n", length($safe), $opt_sanitize;
    exit 0;
}

my $rep = $guard->audit_csv_string($raw);
if ($opt_json) {
    print JSON::PP->new->utf8->canonical->pretty->encode($rep);
    exit 0;
}

printf "CSV Rows: %d | Cells: %d | CWE-1236 Findings: %d | Clean: %s\n",
    $rep->{row_count}, $rep->{cell_count}, $rep->{finding_count}, ($rep->{clean} ? 'YES' : 'NO');
for my $f (@{ $rep->{findings} }) {
    printf "  [%s] %s: %s -> %s\n", $f->{risk}, $f->{a1_ref}, $f->{vector}, $f->{preview};
}

exit 0;

__END__

=head1 NAME

cwe1236-audit - Command-line MITRE CWE-1236 CSV formula-injection sanitizer and .xlsx/.xlsm security auditor

=head1 SYNOPSIS

    cwe1236-audit export.csv
    cwe1236-audit --sanitize-out safe.csv export.csv
    cwe1236-audit --xlsx --json workbook.xlsm

=head1 AUTHOR

Islam Ayoub (UTILVO) E<lt>info@utilvo.comE<gt>

=cut
