<?php

declare(strict_types=1);

header('Content-Type: text/plain; charset=UTF-8');

$root = __DIR__;
$vendor = $root . '/vendor';
$targets = [
    $root . '/vendor',
    $root . '/vendor/composer',
    $root . '/vendor/symfony',
    $root . '/vendor/symfony/deprecation-contracts',
    $root . '/vendor/composer/autoload_real.php',
    $root . '/vendor/symfony/deprecation-contracts/function.php',
];

if (! is_dir($vendor)) {
    echo "vendor folder not found in {$root}\n";
    exit(1);
}

$errors = [];

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($vendor, FilesystemIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST
);

if (! @chmod($vendor, 0755)) {
    $errors[] = "Failed: {$vendor}";
}

foreach ($iterator as $item) {
    $path = $item->getPathname();
    $mode = $item->isDir() ? 0755 : 0644;

    if (! @chmod($path, $mode)) {
        $errors[] = "Failed: {$path}";
    }
}

clearstatcache();

echo "Vendor permission repair finished.\n\n";

foreach ($targets as $path) {
    if (! file_exists($path)) {
        echo $path . " => missing\n";
        continue;
    }

    $perms = substr(sprintf('%o', fileperms($path)), -4);
    echo $path . " => " . $perms . "\n";
}

echo "\n";

if ($errors !== []) {
    echo "Some paths could not be changed:\n";
    echo implode("\n", $errors) . "\n";
    exit(1);
}

echo "Delete this file after it runs.\n";
