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

require_once __DIR__ . '/../vendor/autoload.php';

use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

const COMPOSER_JSON_DEST = __DIR__ . '/../composer.json';
const SYS_TMP_DIR = '/tmp';
const TMP_DIR = SYS_TMP_DIR . '/FinSearch';
const IGNORED = [
    'FinSearch/.git/\*',
    'FinSearch/.github/\*',
    'FinSearch/.gitignore',
    'FinSearch/.idea/\*',
    'FinSearch/.travis.yml',
    'FinSearch/bin/\*',
    'FinSearch/composer.lock',
    'FinSearch/phpcs.xml',
    'FinSearch/phpunit.xml.dist',
    'FinSearch/tests/\*',
    '*.zip',
];

$logger = new Logger('release');
$formatter = new LineFormatter(null, null, false, true);
$logger->pushHandler((new StreamHandler('php://stdout'))->setFormatter($formatter));

$composerJsonData = json_decode(file_get_contents(COMPOSER_JSON_DEST), true);
$version = $composerJsonData['version'];

$logger->info(sprintf('Creating a release for version %s', $version));
$logger->info('The zip can be uploaded directly to the Shopware Store.');

$logger->info('Running "git stash" to preserve local changes.');
$stash = exec('git stash');
exec('git fetch --all --tags --prune');

$tag = exec(sprintf('git tag -l %s', $version));
$workingBranch = exec('git branch | grep \* | cut -d \' \' -f2');

if (!$tag) {
    $logger->error(sprintf('Tag %s not found.', $version));
    exit(1);
}

exec(sprintf('git checkout tags/%s', $tag));

$logger->info('Copying files...');
exec(sprintf('cp -rf . %s', TMP_DIR));
chdir(TMP_DIR);

$logger->info('Installing dependencies (may remove dev dependencies)...');
exec('composer install --no-dev --optimize-autoloader --prefer-dist');

$logger->info('Adding shopware/core and shopware/storefront to the composer.json.');
$composerJsonData['require']['shopware/core'] = '^6.2||^6.3||^6.4';
$composerJsonData['require']['shopware/storefront'] = '^6.2||^6.3||^6.4';
file_put_contents(
    TMP_DIR . '/composer.json',
    json_encode($composerJsonData, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES)
);

chdir(SYS_TMP_DIR);

$zipFileDest = sprintf('%s/FinSearch-%s.zip', __DIR__ . '/..', $version);
exec(sprintf('zip -r9 %s FinSearch -x %s', $zipFileDest, implode(' ', IGNORED)));

exec('rm -rf "/tmp/FinSearch"');
chdir(__DIR__ . '/..');

$logger->info('Restoring work in progress ...');
exec(sprintf('git checkout %s', $workingBranch));

if ($stash !== 'No local changes to save') {
    exec('git stash pop');
}

$logger->info(sprintf('SUCCESS! The release was successfully created! You can find it in %s', realpath($zipFileDest)));
