#!/bin/perl
=head1 NAME

/usr/lib/obs/service/format_cmake -

=head1 SYNOPSIS

/usr/lib/obs/service/format_cmake [options]

Options:

   --file               File for pattern parsing
   --cmake-directory    Directory in which to list cache variables
   --outfile            File for save (optional)
   --outdir             Output directory
   --noop               Do nothing
=cut

use Getopt::Long;
use Pod::Usage;
use Path::Tiny;
use IPC::Run3;
use File::Util::Tempdir;
use B;
use Data::UUID;
no warnings "deprecated";

our $help, $file, $outfile, $noop, $outdir;
our @cmakedirs;
our $code = 0;
our $tempdir;

if (!defined($tempdir)){
  $tempdir = path(File::Util::Tempdir->get_user_tempdir())->child(Data::UUID->new()->create_hex());
  mkdir($tempdir);
} else {
  $tempdir = path($tempdir);
}

my $configdir = $tempdir->child('config');
my $cachedir = $tempdir->child('cache');

mkdir ($configdir);

GetOptions(
    'help'                 => \$help,
    'cmake-directory=s@'   => \@cmakedirs,
    'file=s'               => \$file,
    'outfile=s'            => \$outfile,
    'outdir=s'             => \$outdir,
    'noop=s'               => \$noop
);

if ($noop eq "enable"){
  exit(0);
}

if ( $help ){
   retlabel:
   pod2usage({-exitval => $code, -input => __FILE__});
}

if ((!defined($file)) || (scalar @cmakedirs == 0) || (!defined($outdir))){
    $code = 1;
    goto retlabel;
}

$file = [glob($file)]->[0];

$configfile = path("CMakeLists.txt")->absolute($configdir);

my $cmakelists_out_handle = $configfile->openw_utf8();

sub set_proc{
  my ($variable, $type, $value) = @_;
  $value = B::cstring($value);
  return "set($variable $value CACHE $type '' FORCE)";
}

sub texthandler{
  if (index($_, '--') != 0){
    $_ =~ s/^(\w+):(\w+)=(.*)/set_proc($1, $2, $3)/ge;
    print $cmakelists_out_handle "$_\n";
  }
}

for (@cmakedirs){
    run3(['cmake', '-L', path("CMakeLists.txt")->absolute($_), '-B', $cachedir ], \undef, \&texthandler, \undef);
}

if (!defined($outfile)){
  $outfile = $file;
}

$file = B::cstring(path($file)->absolute());
$outfile = B::cstring($outfile);

print $cmakelists_out_handle "configure_file( $file $outfile @ONLY )";

system('cmake', '-P', $configfile, '-S', $configdir, '-B', $outdir);
