#!/usr/bin/env perl

use strict ;
use IPC::System::Simple qw(systemx runx capturex $EXITVAL);
use String::ShellQuote ;
use File::Basename;

our @switches = qw(
    4.05.0
    4.06.0
    4.06.1
    4.07.0
    4.07.1
    4.08.0
    4.08.1
    4.09.0
    4.10.0
    4.10.1
    4.10.2
    4.11.0
    4.11.1
    4.11.2
    4.12.0
    4.13.0
    4.13.1
    4.14.0~alpha1
    ) ;

our $verbose = 0 ;

{
  while (@ARGV) {
    if ($ARGV[0] eq '--switches') {
      shift @ARGV ;
      @switches = split(m/,/, shift @ARGV) ;
    }
    elsif ($ARGV[0] eq '-v') {
      shift @ARGV ;
      $verbose = 1 ;
    }
    else { last ; }
  }
}

{
  my $wd = dirname(dirname($0)) ;

  my $top = $ENV{'TOP'} || $wd;

  my $currs = `opam switch show` ;
  chomp $currs ;

  my %newenv ;
  $newenv{'PATH'} = "$top/local-install/bin:$ENV{'PATH'}" ;
  $newenv{'OCAMLPATH'} = "$top/local-install/lib:" ;

  local %ENV = (%ENV, %newenv) ;

  for my $s (@switches) {
    v_systemx([0], ["opam", "switch", $s]) ;
    if (! $verbose) {
      print STDERR "="x16, $s, "="x16, "\n";
    }
    v_systemx([0], [@ARGV]) ;
  }
  v_systemx([0], ["opam", "switch", $currs]) ;
}

sub v_systemx {
  croak( "v_systemx: must specify exit codes") unless (ref($_[0]) eq 'ARRAY') ;
  my $codes = shift ;
  my @cmd = @{ shift @_ } ;
  my %args = @_ ;

  print STDERR join(' ', map { shell_quote($_) } @cmd)."\n" if $main::verbose ;

  return runx($codes, @cmd) ;
}

