#!/usr/bin/perl
#################################################################################### arduino buildbot (mwx'2025)
use Getopt::Std;getopts('sb');
use Time::HiRes qw( usleep );
$ots=0;

opendir(DIR,"/dev");$n=0;                                                                    # search for device
while($d=readdir(DIR)) {
  if ($d=~/^ttyACM1/) {
    $adev="/dev/$d";
    $n++;
  }
}
$dev=$adev if ($n>=1);
$dev=$ARGV[0] if ($ARGV[0]=~/^\/dev\//);

opendir(DIR,".");while($f=readdir(DIR)) { $file=$f if ($f=~/\.ino$/) }

$fqbn="arduino:avr:mega";

if ($opt_s) { ################################################################################ screen start loop
  for(;;) {
    if (!-f "/tmp/buildbot.lock.screen") {
      system("arduino-cli monitor -p $dev"); 
    }
    sleep(4);
  }
  exit;  
}


for (;;) { ##################################################################################### main build loop
  
  $ts=(stat($file))[9];
  
  if ($ots != $ts) {
    print "\033[2J\033[1;1H";

    my(@z)=localtime($ts);$z[4]+=1;$z[5]-=100;$z[6]+=1;
    $z=sprintf("%02d\.%02d\.%02d %02d\:%02d",$z[3],$z[4],$z[5],$z[2],$z[1]);
    print "\n\033[38;5;044m--- $z: start compiling/upload ($file|$dev|$fqbn) ---\033[0m\n\n";
    $ots=$ts;
        
    system("arduino-cli compile --fqbn $fqbn");
    
    $e=$?>>8;
    
    if (!$e) {
      print "\n\033[38;5;105m--- $z: compiling done ---\033[0m\n";
    

    if ($dev!~/^\s*$/) {
    
      system("touch /tmp/buildbot.lock.screen");
  		
  		system('killall arduino-cli > /dev/null 2>&1') if (!$e);
      system("arduino-cli upload -p $dev --fqbn $fqbn") if (!$e);
  
      $e=$?>>8;
  
      my(@z)=localtime($ts);$z[4]+=1;$z[5]-=100;$z[6]+=1;
      $z=sprintf("%02d\.%02d\.%02d %02d\:%02d",$z[3],$z[4],$z[5],$z[2],$z[1]);
      if (!$e) {
        print "\033[38;5;209m--- $z: upload finished successfully ($dev) ---\033[0m\n\n";
        system("rm -f /tmp/buildbot.lock.screen");
      }
    }
    }
  }
  last if ($opt_b);
  &usleep(250000);
}

############################################################################################################ END
