backupscript/src/CommandBackup.php
2023-05-31 09:00:20 +00:00

72 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 Symfony\Component\Yaml\Yaml;
use Symfony\Component\Yaml\Exception\ParseException;
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 {
$config = Yaml::parseFile($input->getArgument('config'));
} catch (ParseException $e) {
$io->error('Unable to parse the YAML string: '. $e->getMessage());
return Command::FAILURE;
}
$rclone = new Rclone\Rclone();
$io->info("Rclone version: ". $rclone->getVersion());
$ntfy = new Ntfy\Ntfy($config['notification']['domain']);
$loader = new ArrayLoader($config['templates']);
$twig = new Environment($loader);
$twig->addExtension(new Twig\AppExtension());
foreach($io->progressIterate( $config['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($config['notification']['topic'], $conf['title'], $message);
}
$io->success("Complete");
return Command::SUCCESS;
}
}