#!/usr/bin/env perl

use strict;
use warnings;

my $dir = ".artifacts.tmp";
my ($token, $id) = @ARGV;
die "usage: $0 [token] [id]" unless defined $token and defined $id;
die "id in bad format" unless $id=~m#^[0-9]+$#;

if(!-d $dir) {
  mkdir($dir) or die "Cannot create directory '$dir', because: $!\n";
}

system(qq(curl --globoff --header "PRIVATE-TOKEN: $token" "https://gitlab.uniworx.de/api/v4/projects/5/pipelines/$id/bridges" > $dir/bridges));
my $pips = pparse("$dir/bridges", {id=>qq#."downstream_pipeline"."id"#}, {name=>""});

my $fe = $pips->{frontend}{id};

die "No frontend pipeline found!" unless $fe;

system(qq(curl --globoff --header "PRIVATE-TOKEN: $token" "https://gitlab.uniworx.de/api/v4/projects/5/pipelines/$fe/jobs" > $dir/fe-jobs));
my $arte = pparse("$dir/fe-jobs", {id=>""}, {name=>"", web_url=>"", artifacts=>""});

system(qq#curl --output $dir/artifacts.zip --location --header "PRIVATE-TOKEN: $token" "https://gitlab.uniworx.de/api/v4/projects/5/jobs/$arte->{compile}{id}/artifacts"#);


sub pparse {
  my ($file, $numerical, $alpha) = @_;
  my %all = ();
  for my $k(keys %$numerical) {
    $all{$k} = $numerical->{$k} || qq#."$k"#;
  }
  for my $k(keys %$alpha) {
    $all{$k} = $alpha->{$k} || qq#."$k"#;
  }
  my $select = join ', ', map {qq#"$_": $all{$_}#} sort keys %all;
  my $cont = qx(cat $file | jq -c '.[] | {$select}');
  my @cont = split m/\R/, $cont;
  my %ret = ();
  for my $c(@cont) {
    my %block = ();
    for(keys %$numerical) {
      $block{$_} = $1 if $c=~m#"$_":([0-9]+)#;
    }
    for(keys %$alpha) {
      $block{$_} = $1 if $c=~m#"$_":"([^"]*)"#;
    }
    $ret{$block{name}} =\%block;
  }
  return \%ret
}