'use strict';

function s3like(provider) {
  return provider === 's3' || provider === 'minio' || provider === 's3-v4-compat'
    || provider === 'exoscale-sos' || provider === 'digitalocean-spaces' || provider === 'hetzner-objectstorage'
    || provider === 'scaleway-objectstorage' || provider === 'wasabi' || provider === 'backblaze-b2' || provider === 'cloudflare-r2'
    || provider === 'linode-objectstorage' || provider === 'ovh-objectstorage' || provider === 'ionos-objectstorage'
    || provider === 'vultr-objectstorage' || provider === 'upcloud-objectstorage' || provider === 'idrive-e2'
    || provider === 'contabo-objectstorage';
}

exports.up = async function (db) {
    const result = await db.runSql('SELECT * FROM settings WHERE name=?', [ 'backup_storage' ]);
    if (!result.length) return;

    const storageConfig = JSON.parse(result[0].value);
    if (!s3like(storageConfig.provider)) return;

    if (storageConfig.endpoint && !storageConfig.endpoint.match(/^(http:|https:)\/\//)) {
        console.log('migrating backup provider endpoint to https');
        storageConfig.endpoint = `https://${storageConfig.endpoint}`;
    }

    if (storageConfig.provider === 'linode-objectstorage') { // in some old release, we didn't set the region correctly
        const match = storageConfig.endpoint.match(/^https:\/\/(.*).linodeobjects.com$/);
        storageConfig.region = match ? match[1] : storageConfig.region;
        console.log('migrating backup region to', storageConfig.region);
    }

    await db.runSql('UPDATE settings SET value=? WHERE name=?', [ JSON.stringify(storageConfig), 'backup_storage']);

};

exports.down = async function (db) {
};
