#!/usr/bin/env nqp
# Copyright (C) 2014, The Perl Foundation


sub MAIN(*@ARGS) {
    my $program := @ARGS.shift;
    my $backend := @ARGS.shift;
    my $prefix := "";
    say("# This file automatically generated by $program\n");
    while nqp::substr(@ARGS[0], 0, 1) eq '-' && nqp::elems(@ARGS) >= 2 {
        my $op := nqp::shift(@ARGS);
        if $op eq '-f' {
            my $file := nqp::shift(@ARGS);
            my $fh   := open($file, :r, :!chomp);
            while $fh.get -> $line {
                if $line ~~ /\S/ {
                    $line := subst($line, /\s+/, '', :global);
                    nqp::push(@ARGS, $line);
                }
            }
            close($fh);
        }
        elsif $op eq '-p' {
            $prefix := nqp::shift(@ARGS);
        }
        else {
            nqp::die("Unknown command line option '$op'");
        }
    }
    my $stderr := nqp::getstderr();
    for @ARGS -> $file {
        say("#line 1 $prefix$file");
        my $fh := open($file, :r, :!chomp);
        my int $in_cond := 0;
        my int $in_omit := 0;
        my int $line    := 1;
        while $fh.get -> $_ {
            if my $x := $_ ~~ / ^ '#?if' \s+ ('!')? \s* (\w+) \s* $ / {
                nqp::die("Nested conditionals not supported, line $line") if $in_cond;
                $in_cond := 1;
                $in_omit := $x[0] && $x[1] eq $backend || !$x[0] && $x[1] ne $backend;
                print("\n");
            }
            elsif $_ ~~ /^ '#?endif' / {
                unless $in_cond {
                    stderr().say(
                        "#?endif without matching #?if in file $file, line $line"
                    );
                }
                $in_cond := 0;
                $in_omit := 0;
                print("\n");
            }
            elsif $in_omit {
                print("\n");
            }
            elsif nqp::index($_, '#RAKUDO_FLAVOR#') > -1 {
                my str $flavor := nqp::ifnull(
                  nqp::atkey(nqp::getenvhash, 'RAKUDO_FLAVOR'),
                  ""
                );
                print(
                  nqp::join("'$flavor'", nqp::split('#RAKUDO_FLAVOR#', $_))
                );
            }
            elsif $backend eq 'js' && $_ ~~ /'#?js: NFG'/ {
                print(subst($_, /nqp\:\:[chars|substr|iseq_s|iscclass]/,
                    -> $op {$op ~ 'nfg'}, :global));
            }
            else {
                print($_) unless nqp::eqat($_,"# vim:",0);
            }
            $line++;
        }
        close($fh);
    }
    say("\n# vim: set ft=perl6 nomodifiable :");
}

# vim: expandtab sw=4
