<?php

namespace Espo\Custom\Jobs;

use League\Flysystem\{
    Filesystem,
    FilesystemError,
    Local\LocalFilesystemAdapter,
    PhpseclibV2\SftpConnectionProvider,
    PhpseclibV2\SftpAdapter,
    UnixVisibility\PortableVisibilityConverter,
};

use \Espo\Custom\Core\Utils\SpryngUtil;

class SftpGetBackupJobs extends \Espo\Core\Jobs\Base
{
    public function run()
    {
        $em = $this->getEntityManager();
        $integration = $em->getEntity('Integration', 'FtpXYZ');

        $remoteFileSystem = new Filesystem(
            new SftpAdapter(
            new SftpConnectionProvider(
                'aaa.aaa.aaa.aaa', // host (required)
                'ftp_user', // username (required)
                'ftp_password', // password (optional, default: null) set to null if privateKey is used
                null, // private key (optional, default: null) can be used instead of password, set to null if password is set
                null, // passphrase (optional, default: null), set to null if privateKey is not used or has no passphrase
                '9999', // port (optional, default: 22)
                false, // use agent (optional, default: false)
                30, // timeout (optional, default: 10)
                3, // max tries (optional, default: 4)
                null, // host fingerprint (optional, default: null),
                null, // connectivity checker (must be an implementation of 'League\Flysystem\PhpseclibV2\ConnectivityChecker' to check if a connection can be established (optional, omit if you don't need some special handling for setting reliable connections)
            ),
            '/', // root path (required)
            PortableVisibilityConverter::fromArray([
                'file' => [
                    'public' => 0640,
                    'private' => 0604,
                ],
                'dir' => [
                    'public' => 0740,
                    'private' => 7604,
                ],
            ])
        ));

        // BACKUP FILE

        $path = "/var/www/vhosts/ftp_site/backups/";
        $files  = $remoteFileSystem->listContents($path, false);

        $pathLocal = '/Volumes/macOSData/sites/backups/';
        
        $adapter = new \League\Flysystem\Local\LocalFilesystemAdapter( $pathLocal );
        $localFileSystem = new \League\Flysystem\Filesystem($adapter);
        
        $doneFile = '/Volumes/macOSData/sites/backups/doneFile.php';
        $doneArray = explode(PHP_EOL, file_get_contents($doneFile));
        $spryngSms = new SpryngUtil( $em );

        foreach($files as $file)
        {
            if ($file instanceof \League\Flysystem\FileAttributes) {
                $path = $file->path();
                if ( !in_array($path, $doneArray) )
                {
                    $start = microtime(true);
                    try {
                        $response = $remoteFileSystem->readStream($file['path']);
                    } catch (FilesystemError | UnableToReadFile $exception) {
                        $GLOBALS['log']->error( 'SftpGetBackup unable to read remoteFileSystem');
                    }

                    try {
                        $localFileSystem->writeStream( basename($path)  , $response, []);
                        file_put_contents($doneFile, $path .PHP_EOL , FILE_APPEND );
                        $response = $spryngSms->send( '32xxxxx', basename($path) .' => ' .$response  );
                    } catch (FilesystemError | UnableToWriteFile $exception) {
                        $GLOBALS['log']->error( 'SftpGetBackup unable to write localFileSystem'  );
                    }

                }else{
                    $GLOBALS['log']->warning( 'SftpGetBackup remoteFile exists in localFile'  );
                }

            } 
            
            $time_elapsed_secs = microtime(true) - $start;
            $GLOBALS['log']->warning( $time_elapsed_secs  );


        }


        $fileSystemIterator = new \FilesystemIterator('/var/www/backup');
        $now = time();
        foreach ($fileSystemIterator as $file) {
            if ($file->isDir() || $file->getFilename() == 'doneFile.php' ) continue;
            if ($now - $file->getCTime() >= 3600 * 24 * 360) {// 360 days 
                @unlink('/var/www/backup/'.$file->getFilename() );
                $GLOBALS['log']->warning( 'SftpGetBackup deleted one file older than 360 days'  );
            }
        }

        return true;
    }
}
