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

use CarbonPHP\Abstracts\Background;
use CarbonPHP\Abstracts\ColorCode;
use CarbonPHP\Interfaces\iColorCode;

require 'common.php';

[$cmd, $remote, $url] = $argv;

$statusCode = 0;

// @note we readline in php using a shell exec ``; doing it directly will fail with unexpected behavior

// todo - make a changelog and verify tag exists before publishing

Background::executeAndCheckStatus('composer run test');

passthru('git fetch --tags', $statusCode);

if (0 !== $statusCode) {

    ColorCode::colorCode("Failed to pull git hooks.\nHint: if you see `(would clobber existing tag)` above, run `git tag -d [TAG];` where tag is the version number. ie 0.0.0", iColorCode::RED);

    exit(1);

}

// no changes added to commit
// Your branch is up to date with

$revisionCheck = static function () use ($cmd, &$revisionCheck): string {

    $status = shell_exec('git status');

    $status = trim($status);

    $validPush = !str_contains($status, 'Your branch is up to date with');

    if (!$validPush) {

        ColorCode::colorCode("After running git status it appears you have nothing to commit.", iColorCode::YELLOW);

        exit(0);

    }

    $revision = trim(shell_exec('git describe --tags `git rev-list --tags --max-count=1`'));

    $regexRevision = str_replace('.', '\.', $revision);

    $remoteCheck = shell_exec("git ls-remote --tags origin | grep \"$regexRevision\"");

    $out = null === $remoteCheck ? null : trim($remoteCheck);

    $noRevisionOnRemote = empty($out);

    if ($noRevisionOnRemote
        || str_contains($cmd, $revision)
        || str_contains($cmd, 'git tag')
        || str_contains($cmd, 'git push --tags --no-verify')) {

        if ($noRevisionOnRemote) {

            ColorCode::colorCode("Detected that revision ($revision) does not yet exist on the remote.", iColorCode::YELLOW);

            ColorCode::colorCode("If the revision fails to post automatically, you should run (git push --tags).", iColorCode::YELLOW);

            exit(0);

        }

        $deleteTag = 0;

        passthru("git tag -d $revision", $deleteTag);

        if (0 !== $deleteTag) {

            ColorCode::colorCode("Oh no! Looks like the tag $revision is already on the remote. Attempt to automatically resolve failed.", iColorCode::RED);

        }

        ColorCode::colorCode("A revision tagged locally was already detected on the remote. We are attempting to this issue.");

        // this is a recursive call
        return $revisionCheck();

    }

    ColorCode::colorCode("The revision ($revision) was found on the remote ($out)", iColorCode::BACKGROUND_CYAN);

    ColorCode::colorCode("The githook was called for command ($cmd)", iColorCode::BACKGROUND_CYAN);

    return $revision;

};

$revision = $revisionCheck();

$revision_exploded = explode('.', $revision);

if (count($revision_exploded) !== 3) {

    ColorCode::colorCode(
        PHP_EOL . 'Could not determine a valid tag; you may need to manually increment to a valid version number.' . PHP_EOL . PHP_EOL, iColorCode::RED);

}

$addNewTag = static function ($tag, $versionBumpType): void {

    $pushTags = static function($tag, $releaseName = 'patch') {

        // todo get the last major / minor release name and add it to patches automagically
        Background::executeAndCheckStatus("git tag -s -a $tag -m \"release: (" . $releaseName . ") revision: ($tag)\"");

        ColorCode::colorCode('Going to commit a TAG mid GitHook. Output in the CLI will show two pushes to git. This is expected.', iColorCode::MAGENTA);

        Background::executeAndCheckStatus("git push --tags --no-verify");

    };

    ColorCode::colorCode("Adding new tag :: '$tag'");

    if ($versionBumpType === 'patch') {

        $pushTags($tag);

        ColorCode::colorCode("Pushing Git Tag ($tag) Finished (patch).");

        return;

    }

    ColorCode::colorCode('Please enter release name (bolder,maverick,fire,etc):', iColorCode::MAGENTA);

    do {

        $releaseName = `exec < /dev/tty && php -r 'echo (\$r = readline()) ? "Release Name (\$r)" : "";'`;

    } while ($releaseName === '');

    $pushTags($tag, $releaseName);

    do {

        ColorCode::colorCode("Enter a release title and use/reference ($releaseName) (@link: https://github.com/RichardTMiles/CarbonPHP/releases)", iColorCode::MAGENTA);

        $releaseTitle = `exec < /dev/tty && php -r 'echo (\$r = readline()) ? \$r : "";'`;

    } while ($releaseTitle === '');

    Background::executeAndCheckStatus("git tag -a $tag -m \"" . $releaseName . " revision $tag\"");

    ColorCode::colorCode('Please add additional notes (type "done" alone on a new line to complete):', iColorCode::MAGENTA);

    $releaseNotes = '';

    $done = false;

    do {

        $line = `exec < /dev/tty && php -r 'echo (\$r = readline()) ? \$r : "done";'`;

        if ('done' === $line) {

            $done = true;

        } else {

            $releaseNotes .= $line;

        }

    } while (!$done);

    Background::executeAndCheckStatus("gh release create $tag --title '" . preg_quote($releaseTitle, "'") . "' --notes '" . preg_quote($releaseNotes, "'") . "'");

    ColorCode::colorCode("Pushing Git Tag ($tag) Finished ($releaseTitle).");

};

$bumpCurrentRevision = static function () use (&$revision_exploded): string {

    ColorCode::colorCode(<<<SEMVAR
Semantic Versioning Specification (SemVer) (Directly from https://semver.org/)
The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119.

1. Software using Semantic Versioning MUST declare a public API. This API could be declared in the code itself or exist strictly in documentation. However it is done, it SHOULD be precise and comprehensive.

2. A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor version, and Z is the patch version. Each element MUST increase numerically. For instance: 1.9.0 -> 1.10.0 -> 1.11.0.

3. Once a versioned package has been released, the contents of that version MUST NOT be modified. Any modifications MUST be released as a new version.

4. Major version zero (0.y.z) is for initial development. Anything MAY change at any time. The public API SHOULD NOT be considered stable.

5. Version 1.0.0 defines the public API. The way in which the version number is incremented after this release is dependent on this public API and how it changes.

6. Patch version Z (x.y.Z | x > 0) MUST be incremented if only backward compatible bug fixes are introduced. A bug fix is defined as an internal change that fixes incorrect behavior.

7. Minor version Y (x.Y.z | x > 0) MUST be incremented if new, backward compatible functionality is introduced to the public API. It MUST be incremented if any public API functionality is marked as deprecated. It MAY be incremented if substantial new functionality or improvements are introduced within the private code. It MAY include patch level changes. Patch version MUST be reset to 0 when minor version is incremented.

8. Major version X (X.y.z | X > 0) MUST be incremented if any backward incompatible changes are introduced to the public API. It MAY also include minor and patch level changes. Patch and minor versions MUST be reset to 0 when major version is incremented.

9. A pre-release version MAY be denoted by appending a hyphen and a series of dot separated identifiers immediately following the patch version. Identifiers MUST comprise only ASCII alphanumerics and hyphens [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers MUST NOT include leading zeroes. Pre-release versions have a lower precedence than the associated normal version. A pre-release version indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its associated normal version. Examples: 1.0.0-alpha, 1.0.0-alpha.1, 1.0.0-0.3.7, 1.0.0-x.7.z.92, 1.0.0-x-y-z.--.

10. Build metadata MAY be denoted by appending a plus sign and a series of dot separated identifiers immediately following the patch or pre-release version. Identifiers MUST comprise only ASCII alphanumerics and hyphens [0-9A-Za-z-]. Identifiers MUST NOT be empty. Build metadata MUST be ignored when determining version precedence. Thus two versions that differ only in the build metadata, have the same precedence. Examples: 1.0.0-alpha+001, 1.0.0+20130313144700, 1.0.0-beta+exp.sha.5114f85, 1.0.0+21AF26D3----117B344092BD.

11. Precedence refers to how versions are compared to each other when ordered.

    Precedence MUST be calculated by separating the version into major, minor, patch and pre-release identifiers in that order (Build metadata does not figure into precedence).

    Precedence is determined by the first difference when comparing each of these identifiers from left to right as follows: Major, minor, and patch versions are always compared numerically.

    Example: 1.0.0 < 2.0.0 < 2.1.0 < 2.1.1.

    When major, minor, and patch are equal, a pre-release version has lower precedence than a normal version:

    Example: 1.0.0-alpha < 1.0.0.

    Precedence for two pre-release versions with the same major, minor, and patch version MUST be determined by comparing each dot separated identifier from left to right until a difference is found as follows:

    Identifiers consisting of only digits are compared numerically.

    Identifiers with letters or hyphens are compared lexically in ASCII sort order.

    Numeric identifiers always have lower precedence than non-numeric identifiers.

    A larger set of pre-release fields has a higher precedence than a smaller set, if all of the preceding identifiers are equal.

    Example: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0.

SEMVAR
    );

    sleep(1);

    ColorCode::colorCode('Enter version bump type (major, minor, patch [default]): ');

    $versionBumpType = `exec < /dev/tty && php -r 'echo (\$r = readline()) ? \$r : "patch";'`;

    if (false === $versionBumpType) {

        ColorCode::colorCode('Readline failed. Please try again.', iColorCode::RED);

        exit(1);

    }

    if (empty($versionBumpType)) {

        $versionBumpType = 'patch';

    }

    if (!in_array($versionBumpType, ['major', 'minor', 'patch'])) {

        ColorCode::colorCode("Invalid version bump type ($versionBumpType). Please try again.", iColorCode::RED);

        exit(1);

    }

    switch ($versionBumpType) {

        case 'major':

            $revision_exploded[0]++;

            $revision_exploded[1] = 0;

            $revision_exploded[2] = 0;

            return $versionBumpType;

        case 'minor':

            $revision_exploded[1]++;

            $revision_exploded[2] = 0;

            return $versionBumpType;

        default:
        case 'patch':

            $revision_exploded[2]++;

            return $versionBumpType;

    }

};


do {

    $versionBumpType = $bumpCurrentRevision();

    $tag = implode('.', $revision_exploded);

    $revisionExists = shell_exec("git tag | grep $tag");

    ColorCode::colorCode("Revision bump failed, will try again ($tag)", iColorCode::BACKGROUND_YELLOW);

} while (null !== $revisionExists && '' !== trim($revisionExists));

$addNewTag($tag, $versionBumpType);

