backupscript/src/CommandBackup.php
2023-05-31 14:34:35 +00:00

76 lines
2.5 KiB
PHP

<?php
namespace App;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Twig\Environment;
use Twig\Loader\ArrayLoader;
use DateTime;
class CommandBackup extends Command
{
static $defaultName = "backup";
static $defaultDescription = "Start backup to assigned buckets";
protected function configure(): void
{
$this->addArgument('config', InputArgument::OPTIONAL, 'Configuration file', "config.yml");
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$io->title('Start backup process');
$io->info('Opening: '.$input->getArgument('config'));
try {
$app = new App($input->getArgument('config'));
}
catch (\Throwable $e) {
$io->error('Unable to parse the YAML string: '. $e->getMessage());
return Command::FAILURE;
}
$rclone = new Rclone\Rclone();
$rclone->setLogger($app->getLogger()->withName('rclone'));
$ntfy = new Ntfy\Ntfy($app->getConfig()['notification']['domain']);
$ntfy->setLogger( $app->getLogger()->withName('notification'));
$loader = new ArrayLoader($app->getConfig()['templates']);
$twig = new Environment($loader);
$twig->addExtension(new Twig\AppExtension());
foreach ($io->progressIterate($app->getConfig()['backup']) as $conf) {
try {
$template = array();
$template['config'] = $conf;
$template['start'] = new DateTime();
$template['source_size'] = $rclone->getSize($conf['source']);
$template['destination_size_before'] = $rclone->getSize($conf['destination']);
$rclone->copy($conf['source'], $conf['destination'], "6M");
$template['destination_size_after'] = $rclone->getSize($conf['destination']);
$template['end'] = new DateTime();
$message = $twig->render('notify', $template);
} catch (\Throwable $e) {
$message = $e->getMessage();
}
$ntfy->send($app->getConfig()['notification']['topic'], $conf['title'], $message);
}
$io->success("Complete");
return Command::SUCCESS;
}
}