#!/usr/bin/env node

import backuptask from '../backuptask.js';
import database from '../database.js';
import logger from '../logger.js';
import safe from 'safetydance';

const { log } = logger('backupupload');

// --check is used by run-tests to verify sudo access works. Caller must set BOX_ENV (e.g. BOX_ENV=test).
if (process.argv[2] === '--check') {
    console.log('OK');
    process.exit(0);
}

// Main process starts here
const remotePath = process.argv[2];
const format = process.argv[3];
const dataLayoutString = process.argv[4];

log(`Backing up ${dataLayoutString} to ${remotePath}`);

process.on('SIGTERM', function () {
    process.exit(0);
});

// this can happen when the backup task is terminated (not box code)
process.on('disconnect', function () {
    log('parent process died');
    process.exit(0);
});

// send progress every n seconds
function throttledProgressCallback(msecs) {
    let lastProgress = null;

    return function (progress) {
        const now = Date.now();
        if (lastProgress && ((now - lastProgress) < msecs)) return;
        process.send(progress);
        lastProgress = now;
    };
}

await database.initialize();

const [uploadError, result] = await safe(backuptask.upload(remotePath, format, dataLayoutString, throttledProgressCallback(5000)));
log('upload completed. error: %o', uploadError);

process.send({ result, errorMessage: uploadError?.message });

process.exit(uploadError ? 50 : 0);
