const {app} = require('electron');
const log = require('electron-log');
const fs = require('fs');
const path = require('path');
const isDev = require('electron-is-dev');

const rename = () => {
    try {
        if ( isDev ) {
            return log.warn('helper:rename-app-file', 'is development mode');
        } else if ( process.platform !== 'linux' ) {
            return log.warn('helper:rename-app-file', 'platform not linux');
        }

        const homeDirPath = app.getPath('home');
        const version = app.getVersion();
        const ext = '.AppImage';
        const name = `${app.name}-v${version+ext}`;

        fs.readdir(homeDirPath, (err, filenames) => {
            if (err) {
                return log.error('helper:rename-app-file.rename(): fs.readdir(%userData%)');
            }

            for ( let fileIndex = 0; fileIndex < filenames.length; fileIndex++ ) {
                const filename = filenames[fileIndex];
                const filenameObj = path.parse(filename);

                if ( filenameObj.ext === ext && filenameObj.name.indexOf(app.name) >= 0 ) {
                    if ( filenameObj.name.indexOf(version) < 0 ) {
                        fs.renameSync(path.join(homeDirPath, filename), path.join(homeDirPath, name));
                    }

                    break;
                }
            }
        });
    } catch (e) {
        log.error('helper:rename-app-file has broken', e);
    }
};

module.exports = rename;
