#!/usr/bin/env php
<?php
declare(strict_types = 1);

/**
 * @param string $command
 * @param bool $breakOnFailure
 * @return array
 */
function _exec(string $command, bool $breakOnFailure = true): array
{
    $output = [];
    exec($command, $output, $returnVar);

    if ($breakOnFailure && $returnVar) {
        throw new \RuntimeException("Error $returnVar executing command: $command");
    }

    return $output;
}

/**
 * @param string $message
 */
function _echo(string $message)
{
    echo $message . PHP_EOL;
}

$workingFolderPath = ".";
$git = "git -C " . escapeshellarg($workingFolderPath);

// Clean working directory
_exec("$git reset --hard");
_exec("$git clean -f -d");
_exec("$git fetch -p");

// Stuff
$developmentLine = _exec("$git rev-parse --abbrev-ref HEAD");
$developmentLine = end($developmentLine);
_echo("Current branch: $developmentLine");

$branchVersionParts = explode('.x', $developmentLine);
$versionPrefix = $branchVersionParts[0];
$latestStableVersion = _exec(
    "$git --no-pager tag --sort version:refname  | grep -v -F '-' | grep '^"
    . preg_quote($versionPrefix)
    . "' | tail -n 1"
);

$newVersion = $branchVersionParts[0] . '.0';
if (!empty($latestStableVersion)) {
    $latestStableVersion = end($latestStableVersion);
    _echo("Latest stable version: $latestStableVersion");


    $currentVersionParts = explode('.', $latestStableVersion);
    $currentVersionParts[2] += 1;
    $newVersion = implode('.', $currentVersionParts);
}

_echo("New version: $newVersion");
_echo("Pushing tag...");

_exec("$git tag $newVersion");
_exec("$git push origin $developmentLine --tags");
