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

/**
 * coffeephp_exec_psalm
 *
 * Copyright 2020 Danny Damsky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package coffeephp\quality-tools
 * @author Danny Damsky <dannydamsky99@gmail.com>
 * @since 2020-09-12
 */

declare(strict_types=1);

$ds = DIRECTORY_SEPARATOR;
$eol = PHP_EOL;

$composerInstall = null;
foreach (
    [
        dirname(__DIR__, 3) . "{$ds}autoload.php",
        dirname(__DIR__, 2) . "{$ds}vendor{$ds}autoload.php",
        dirname(__DIR__) . "{$ds}vendor{$ds}autoload.php"
    ]
    as $file
) {
    if (file_exists($file)) {
        $composerInstall = $file;
        break;
    }
}

if ($composerInstall === null) {
    fwrite(
        STDERR,
        "You need to set up the project dependencies using Composer.{$eol}"
    );
    exit(1);
}

$basedir = dirname($composerInstall, 2);
chdir($basedir);

$psalmInstall = "{$basedir}{$ds}vendor{$ds}vimeo{$ds}psalm{$ds}psalm";

$psalmXmlLocation = "{$basedir}{$ds}psalm.xml";

if (!is_file($psalmXmlLocation)) {
    copy(
        "{$basedir}{$ds}vendor{$ds}coffeephp{$ds}quality-tools{$ds}provide{$ds}psalm.xml",
        $psalmXmlLocation
    );
}

$arguments = $argv;
array_shift($arguments);

$command = [
    PHP_BINARY,
    $psalmInstall,
    ...$arguments
];

$handle = popen(implode(' ', $command), 'r');

if (!$handle) {
    fwrite(
        STDERR,
        "Failed to execute psalm file: $psalmInstall{$eol}"
    );
    exit(1);
}

while (!feof($handle)) {
    echo fread($handle, 1024);
    flush();
}

$returnCode = pclose($handle) === 0 ? 0 : 1;
exit($returnCode);
