#!/usr/bin/env perl

use strict;
use warnings;

my $LATEST_CLANG_NIGHTLY = "13";

my $image = shift;
my $cross_compile = shift;

my $failures = 0;
my $PASS = "\033[32mPASS\033[m";
my $FAIL = "\033[31mFAIL\033[m";


sub check($$) {
  my ($name, $command) = @_;
  my $output = `$command 2>&1`;
  my $rc = $?;
  if ($rc == 0) {
    print STDERR "${PASS} - ${name} (\`${command}\`)\n";
  } else {
    print STDERR "${FAIL} - ${name} (\`${command}\`)\n";
    $failures++;
  }
}

sub check_program($) {
  my $program = shift;
  check("${program} in PATH", "which ${program}");
}

sub check_base_image() {
  check_program("bash");
  check_program("bc");
  check_program("bison");
  check_program("bzip2");
  check_program("ccache");
  check_program("cpio");
  check_program("flex");
  check_program("git");
  check_program("gzip");
  check_program("lzop");
  check_program("lz4");
  check_program("make");
  check_program("rsync");
  check_program("socat");
  check_program("tar");
  check_program("wget");
  check_program("xz");
  check_program("zstd");
}

sub check_toolchain_image() {
  my ($arch, $compiler, $version);
  if ($image =~ /^(.*)_(.*)$/) {
    $arch = $1;
    $compiler = $2;
  } else {
    $compiler = $image;
  }
  if ($compiler =~ /^(.*)-(nightly|\d+)$/) {
    $compiler = $1;
    $version = $2;
    if ($compiler eq "clang" && $version eq "nightly") {
      $version = $LATEST_CLANG_NIGHTLY;
    }
  }

  $arch ||= `arch`; chomp $arch;
  my @prefixes = ("");
  push @prefixes, $cross_compile if $cross_compile;
  for my $prefix (@prefixes) {
    check_program($prefix . $compiler) unless ($prefix ne "" && $compiler =~ /clang/);
    check_program($prefix . "ld");
    check_program($prefix . "as");
  }

  if ($version && $version =~ /^\d+$/) {
    my $compiler_bin = ($cross_compile && $compiler !~ /clang/) ? ($cross_compile . $compiler) : $compiler;
    my $actual_version = `${compiler_bin} -dumpversion`;
    chomp $actual_version;
    like($actual_version, qr/^${version}(\.\d+)*/, "${compiler_bin} version ${version}");
  }

  if ($compiler =~ /clang/) {
    check_program("ld.lld");
    check_program("llvm-as");
  }
}

exit(0) if ($image =~ /^ci-/);
check_base_image();
check_toolchain_image unless ($image =~ /^base-/);

if ($failures > 0) {
  exit(1)
}
