#!perl

use 5.010;
use alienfile;

use lib 'util';
use MyInstallUtil;

use Config;

# We download from plotly-orca's github repo releases.

my $kaleido_version = 'v0.2.1';

my $github_base_url = "https://github.com/plotly/Kaleido/releases/download";

sub download_url {
    my $kaleido_version = shift;

    my $make_url_github = sub {
        join( '/', $github_base_url, $kaleido_version, $_[0] );
    };

    my $filename;
    if ( $^O eq 'linux' ) {
        $filename = sprintf( "kaleido_linux_%s.zip",
            $Config{archname} =~ /^(?:arm64|aarch64)/ ? 'arm64' : 'x64');
    }
    elsif ( $^O eq 'darwin' ) {
        $filename = sprintf( "kaleido_mac_%s.zip",
            $Config{archname} =~ /^(?:arm64|aarch64)/ ? 'arm64' : 'x64');
    }
    elsif ( $^O eq 'MSWin32' ) {
        $filename = sprintf( "kaleido_win_%s.zip",
            ( $ENV{PROCESSOR_ARCHITECTURE} // '' ) eq 'x86' ? 'x86' : 'x64' );
    }
    else {
        die 'Unsupported OS';
    }
    return $make_url_github->($filename);
}

configure {
    requires 'File::Copy::Recursive' => 0;
    requires 'File::Which'           => 0;
    requires 'IPC::Run'              => 0;
    requires 'JSON'                  => 0;
};

probe sub {
    eval { MyInstallUtil::detect_kaleido_version() };
    if ($@) {
        warn "Failed to detect kaleido from system";
        return 'share';
    }
    else {
        warn "Detected kaleido from system";
        return 'system';
    }
};

share {
    require File::Copy::Recursive;

    start_url( $ENV{ALIEN_PLOTLY_KALEIDO_DOWNLOAD_URL}
          || download_url($kaleido_version) );

    plugin 'Download';
    plugin 'Extract' => 'zip';

    build sub {
        my ($build) = @_;

        my $extract = $build->install_prop->{extract};
        my $prefix  = $build->install_prop->{prefix};

        File::Copy::Recursive::dircopy( $extract, $prefix );
    };

    gather sub {
        my ($build) = @_;

        $ENV{PATH} = join(
            $Config{path_sep},
            $build->install_prop->{prefix},
            $ENV{PATH} // ''
        );
        $build->runtime_prop->{version} =
          MyInstallUtil::detect_kaleido_version();
    };
};