# A build system class for handling ocaml-dune based projects.
#
# Copyright: © 2023 Stéphane Glondu
# License: GPL-2+

package Debian::Debhelper::Buildsystem::ocaml_dune;

use strict;
use warnings;

use JSON qw(decode_json);

use parent qw(Debian::Debhelper::Buildsystem);
use Config;

sub DESCRIPTION {
    "OCaml Dune";
}

sub new {
    my $class = shift;
    my $this  = $class->SUPER::new(@_);
    return $this;
}

sub check_auto_buildable {
    my ( $this, $step ) = @_;
    return -e $this->get_sourcepath("debian/debian-dune");
}

sub get_dh_ocaml_config {
    my $this = shift;
    my $file = $this->get_sourcepath("debian/dh-ocaml.conf.json");

    open my $fh, '<:encoding(UTF-8)', $file
        or return {};

    local $/;
    my $json_text = <$fh>;
    close $fh;

    return decode_json($json_text);
}

sub get_dune_package_names {
    my $this = shift;
    my @names;
    open( FH, "<", $this->get_sourcepath("debian/debian-dune") );
    while (<FH>) {
        chomp;
        my @x = split(/\s+/, $_);
        push( @names, $x[0] );
    }
    close(FH);
    return @names;
}

sub get_dune_package_name_list {
    my $this = shift;
    return join( ",", $this->get_dune_package_names() );
}

sub get_dune_parallel {
    my $this     = shift;
    my $parallel = $this->get_parallel();
    my @result;
    if ( $parallel > 0 ) {
        push( @result, "-j" );
        push( @result, $parallel );
    }
    return @result;
}

sub build {
    my $this = shift;
    $this->doit_in_sourcedir( "dune", "build", $this->get_dune_parallel(),
        "-p", $this->get_dune_package_name_list(), @_ );
}

sub test {
    my $this = shift;
    $this->doit_in_sourcedir( "dune", "runtest", $this->get_dune_parallel(),
        "-p", $this->get_dune_package_name_list() );
}

sub install {
    my $this = shift;
    my $ocaml_stdlib_dir = `ocamlc -where`;
    chomp($ocaml_stdlib_dir);
    my $config = $this->get_dh_ocaml_config();
    my $dune_layout_version = $config->{"dune_layout_version"} // 0;
    if ($dune_layout_version == 1) {
      $this->doit_in_sourcedir( "dune", "install",
                                "--destdir=debian/tmp",
                                "--prefix=/usr",
                                "--libdir=$ocaml_stdlib_dir",
                                "--etcdir=/etc",
                                "--datadir=/usr/share/ocaml-dune/data",
                                "--docdir=/usr/share/ocaml-dune/doc",
                                "--mandir=/usr/share/ocaml-dune/man",
                                $this->get_dune_package_names() );
    } else {
      $this->doit_in_sourcedir( "dune", "install",
                                "--destdir=debian/tmp",
                                "--prefix=/usr",
                                "--libdir=$ocaml_stdlib_dir",
                                $this->get_dune_package_names() );
    }
}

sub clean {
    my $this = shift;
    $this->doit_in_sourcedir( "dune", "clean" );
}

1
