<?php
namespace Deployer;

require 'recipe/common.php';
require 'contrib/rsync.php';
require 'contrib/cachetool.php';

set('bin/php', function () {
    return '/run/current-system/sw/bin/php';
});

set('rsync_src', '../');

import(__DIR__ . '/servers.yaml');

$sharedDirectories = [
    'public/fileadmin',
    'var'
];
set('shared_dirs', $sharedDirectories);

$sharedFiles = [
    '.env',
    'config/system/additional.php',
];
set('shared_files', $sharedFiles);

$writeableDirectories = [
    'public/typo3temp'
];
set('writable_dirs', $writeableDirectories);

$exclude = [
    '.composer-cache',
    'CODE_OF_CONDUCT.md',
    'build',
    '.git*',
    '.ddev',
    '.editorconfig',
    '.idea',
    '.php-cs-fixer.php',
    'phpstan.neon',
];

set('rsync', [
    'exclude' => array_merge($sharedDirectories, $sharedFiles, $exclude),
    'exclude-file' => false,
    'include' => [],
    'include-file' => false,
    'filter' => ['dir-merge,-n /.gitignore'],
    'filter-file' => false,
    'filter-perdir' => false,
    'flags' => 'avz',
    'options' => ['delete'],
    'timeout' => 300
]);

task('typo3:extension:setup', function () {
    cd('{{release_path}}');
    run('{{bin/php}} bin/typo3 extension:setup');
});

task('typo3:cache:flush', function() {
    cd('current');
    run('{{bin/php}} bin/typo3 cache:flush');
});

task('typo3:cache:warmup', function() {
    cd('current');
    run('{{bin/php}} bin/typo3 cache:warmup');
});

task('typo3:language:update', function() {
    cd('current');
    run('{{bin/php}} bin/typo3 language:update');
});

// needed for t3o infrastructure
task('php:reload', function() {
    run('php-reload');
})->select('stage=contentmaster');

task('php:reload-prod', function() {
    run('php-reload');
})->select('stage=production');

// Because we are using rsync, this task is disabled
// to avoid to trigger git
task('deploy:update_code')->hidden()->disable();

task('release:create', [
    'deploy:prepare',
    'rsync',
    'deploy:vendors',
    'deploy:shared',
    'deploy:writable',
    'typo3:extension:setup',
    'deploy:unlock',
    'deploy:success'
]);

task('release:switch', [
    'deploy:symlink',
    'php:reload',
    'php:reload-prod',
    'typo3:cache:flush',
    'typo3:language:update',
    'typo3:cache:warmup',
    'deploy:unlock',
    'deploy:cleanup',
    'deploy:success'
]);

task('deploy', [
    'deploy:prepare',
    'rsync',
    'deploy:vendors',
    'deploy:shared',
    'deploy:writable',
    'typo3:extension:setup',
    'deploy:symlink',
    'php:reload',
    'php:reload-prod',
    'typo3:cache:flush',
    'typo3:language:update',
    'typo3:cache:warmup',
    'deploy:unlock',
    'deploy:cleanup',
    'deploy:success'
]);

host('stage')
    ->set('cachetool', '/var/run/phpfpm/lena-schilling.cloonar.dev.sock');

host('production')
    ->set('cachetool', '/var/run/phpfpm/lena-schilling.at.sock');

after('deploy:symlink', 'cachetool:clear:opcache');
// unlock after failure
after('deploy:failed', 'deploy:unlock');
