#!/usr/bin/perl

use strict;
use Cwd;

open(my $file, '<', 'github_plugins') or die;

if(($ARGV[0]||'') eq 'help')
{
  print
  "broken     show broken CI\n" .
  "checkout   checkout all repos\n" .
  "i18nupdate send I18n updates (don't use without checking before)\n" .
  "reset      reset all changes\n" .
  "status     show current repository states\n" .
  "\n" .
  "<default>  do pullrequests\n";
}
elsif(($ARGV[0]||'') eq 'checkout')
{
  for my $plugin (<$file>)
  {
    chomp($plugin);
    system('git','clone',"https://github.com/JOSM/$plugin");
  }
}
elsif(($ARGV[0]||'') eq 'status')
{
  my $dir = cwd();
  for my $plugin (<$file>)
  {
    print($plugin);
    chomp($plugin);
    chdir($plugin);
    system('git','status');
    chdir($dir);
  }
}
elsif(($ARGV[0]||'') eq 'reset')
{
  my $dir = cwd();
  for my $plugin (<$file>)
  {
    print($plugin);
    chomp($plugin);
    chdir($plugin);
    system('git','reset','--hard','HEAD');
    system('git','pull');
    chdir($dir);
  }
}
elsif(($ARGV[0]||'') eq 'i18nupdate')
{
  my $dir = cwd();
  for my $plugin (<$file>)
  {
    print($plugin);
    chomp($plugin);
    chdir($plugin);
    my $p = Cwd::abs_path('data');
    for my $file (glob "$p/*.lang")
    {
      system('git','add',$file);
      system('git','add',$file);
    }
    system('git','commit','-m','I18n update');
    system('git','remote','set-url','origin',"git\@github.com:JOSM/$plugin.git");
    system('git','push');
    chdir($dir);
  }

}
elsif(($ARGV[0]||'') eq 'broken')
{
  my $dir = cwd();
  my $branch = 'master';
  for my $plugin (<$file>)
  {
    chomp($plugin);
    chdir($plugin);
    my $workflow = `gh run list --limit 1 --workflow 'Java CI' --branch $branch --json databaseId --jq '.[].databaseId'`;
    chomp($workflow);
    my $conclusion = 'not implemented';
    if($workflow ne '')
    {
        $conclusion = `gh run view $workflow --json conclusion --jq .conclusion`;
        chomp($conclusion);
    }
    if($conclusion ne 'success')
    {
      print($plugin . "\n");
    }
    chdir($dir);
  }
}
else
{
  my $dir = cwd();
  for my $plugin (<$file>)
  {
    print($plugin);
    chomp($plugin);
    chdir($plugin);
    system('git','pull');
    chdir($dir);
  }
}
close($file);