#!/usr/bin/env php
<?php

if ($argc != 2) {
    echo "Usage: {$argv[0]} <version>\n";
    exit(1);
}

$version = $argv[1];

if (!preg_match('/[0-9]+.[0-9]+.[0-9]+/', $version)) {
    echo "Error: Version format not recognised\n";
    exit(1);
}

if (!$changelog = file_get_contents(__DIR__ . '/../vendor/cucumber/cucumber/gherkin/CHANGELOG.md')) {
    echo "Error: Could not read changelog\n";
    exit(1);
}

if (!preg_match('/(?<changes>##\s+\['.preg_quote($version).'\].*?)^##\s/ms', $changelog, $matches)) {
    echo "Error: Could not find version $version in changelog\n";
    exit(1);
}

['changes' => $changes] = $matches;

echo "Found changelog:\n$changes";

if (getenv('GITHUB_ACTIONS')) {
    $changes = strtr($changes, ["%" => "%25", "\r" => '%0D', "\n" => '%0A', ':' => '%3A', ',' => '%2C']);
    echo "::set-output name=changelog::$changes\n";
}
