let { exec } = require('child_process');
const fs = require('fs');
const path = require('path');

let optionsDefault = {
  baseDir: '/home/pi', //根路径
  ktLog: {
    i: (msg) => {
      console.log(msg);
    },
  },
  productName: '',
  name: 'cpepm',
};
let ifUpdateApplication = false;
/**
 * linux升级更新Deb包
 * @param {*} data {
 * newTerminalAppResUrl   更新包下载地址
 * newTerminalAppVersion  更新包版本号
 * }
 * @param {*} Options {
 * ktLog   ktLog实例
 * baseDir: '/home/pi', //根路径
 * productName:  //当前版本的项目名称
 * name:'cpepm'  //package.json 中的name值
 *
 * }
 * @returns {code: 1 } 1成功 2失败
 */
function linuxUpdateDeb(data, Options) {
  const { baseDir, ktLog, name, productName } = Options;
  return new Promise((resolve, reject) => {
    if (ifUpdateApplication) {
      ktLog.i('程序正在升级不在处理升级指令');
      return resolve({ code: 2 });
    }
    Options = Object.assign(optionsDefault, Options);
    if (!data.newTerminalAppResName) {
      data.newTerminalAppResName = data.newTerminalAppResUrl.substring(data.newTerminalAppResUrl.lastIndexOf('/') + 1, data.newTerminalAppResUrl.length);
    }
    ifUpdateApplication = true;
    let desktopDebPath = `${baseDir}/Desktop/${data.newTerminalAppResName}`;
    let desktopAppImagePath = `${baseDir}/Desktop/${productName}.AppImage`;
    let autostartDesktop = `${baseDir}/.config/autostart/${name.toUpperCase()}.desktop`;
    let autostartStartupSh = `${baseDir}/.config/autostart/Startup${name.toLocaleUpperCase()}.sh`;
    //删除Deb安装包
    if (fs.existsSync(desktopDebPath)) {
      fs.unlinkSync(desktopDebPath);
    }
    ktLog.i('正在升级程序,开始下载Deb安装包：' + data.newTerminalAppResUrl);
    exec(` wget --timeout=1800 --tries=6 --waitretry=300 -c -P  ${baseDir}/Desktop ${data.newTerminalAppResUrl} `, { timeout: 1000 * 60 * 30 }, (error, stdout, stderr) => {
      if (error) {
        ifUpdateApplication = false;
        ktLog.i('下载文件错误取消升级：' + error);
        return resolve({ code: 2 });
      }
      try {
        fs.chmodSync(desktopDebPath, '777');
        exec(`dpkg -l|grep ${name.toLowerCase()}`, (error, stdout, stderr) => {
          if (stdout.includes(`${name.toLowerCase()}`)) {
            exec(`sudo dpkg --purge ${name.toLowerCase()}`, (error, stdout, stderr) => {
              if (error) {
                ktLog.i('卸载已安装' + name.toLowerCase() + '，deb包错误' + error);
                ifUpdateApplication = false;
                return resolve({ code: 2 });
              }
              ktLog.i('卸载已安装' + name.toLowerCase() + '，deb完成');
              exec(`sudo dpkg -i ${desktopDebPath}`, (error, stdout, stderr) => {
                if (error) {
                  ktLog.i('安装Deb软件包报错：' + error);
                  ifUpdateApplication = false;
                  return resolve({ code: 2 });
                }
                ktLog.i('安装Deb软件包成功，进行设置开机自启动，删除相关文件');
                fs.copyFile(`/usr/share/applications/${name.toLowerCase()}.desktop`, `${baseDir}/.config/autostart/${name.toLowerCase()}.desktop`, (error) => {
                  if (error) {
                    ktLog.i('设置开机自启动.desktop报错：' + error);
                    ifUpdateApplication = false;
                    return resolve({ code: 2 });
                  }
                  //删除Deb安装包
                  if (fs.existsSync(desktopDebPath)) {
                    fs.unlinkSync(desktopDebPath);
                  }
                  //删除桌面AppImage包、开机自启动文件
                  if (fs.existsSync(desktopAppImagePath)) {
                    fs.unlinkSync(desktopAppImagePath);
                    if (fs.existsSync(autostartDesktop)) {
                      fs.unlinkSync(autostartDesktop);
                    }
                    if (fs.existsSync(autostartStartupSh)) {
                      fs.unlinkSync(autostartStartupSh);
                    }
                  }
                  ktLog.i('更新成功');
                  ifUpdateApplication = false;
                  return resolve({ code: 1 });
                });
              });
            });
          } else {
            exec(`sudo dpkg -i ${desktopDebPath}`, (error, stdout, stderr) => {
              if (error) {
                ktLog.i('安装Deb软件包报错：' + error);
                ifUpdateApplication = false;
                return resolve({ code: 2 });
              }
              ktLog.i('安装Deb软件包成功，进行设置开机自启动，删除相关文件');
              fs.copyFile(`/usr/share/applications/${name.toLowerCase()}.desktop`, `${baseDir}/.config/autostart/${name.toLowerCase()}.desktop`, (error) => {
                if (error) {
                  ktLog.i('设置开机自启动.desktop报错：' + error);
                  ifUpdateApplication = false;
                  return resolve({ code: 2 });
                }
                //删除Deb安装包
                if (fs.existsSync(desktopDebPath)) {
                  fs.unlinkSync(desktopDebPath);
                }
                //删除桌面AppImage包、开机自启动文件
                if (fs.existsSync(desktopAppImagePath)) {
                  fs.unlinkSync(desktopAppImagePath);
                  if (fs.existsSync(autostartDesktop)) {
                    fs.unlinkSync(autostartDesktop);
                  }
                  if (fs.existsSync(autostartStartupSh)) {
                    fs.unlinkSync(autostartStartupSh);
                  }
                }
                ktLog.i('更新成功');
                ifUpdateApplication = false;
                return resolve({ code: 1 });
              });
            });
          }
        });
      } catch (e) {
        ifUpdateApplication = false;
        ktLog.i('升级Deb安装包异常：' + e);
        return resolve({ code: 2 });
      }
    });
  });
}

/**  */
/**
 * linux升级更新AppImage包
 * @param {*} data {
 * newTerminalAppResUrl   更新包下载地址
 * newTerminalAppVersion  更新包版本号
 * }
 * @param {*} Options {
 * ktLog   ktLog实例
 * baseDir: '/home/pi', //根路径
 * productName:  //当前版本的项目名称
 * name:'cpepm'  //package.json 中的name值
 *
 *
 * }
 * @returns {code: 1 } 1成功 2失败
 */
function linuxUpdateAppImage(data, Options) {
  return new Promise((resolve, reject) => {
    const { baseDir, ktLog, name, productName } = Options;
    if (ifUpdateApplication) {
      ktLog.i('程序正在升级不在处理升级指令');
      return resolve({ code: 2 });
    }
    Options = Object.assign(optionsDefault, Options);
    ifUpdateApplication = true;
    let startPaht = baseDir + '/Desktop/';
    let lastName = '.AppImage';
    let writePath = startPaht + data.newTerminalAppVersion + lastName;
    let oldFilePath = startPaht + productName + lastName;
    let alerName;
    // 安装版本和当前版本一样的先修改当前版本名称
    if (productName == data.newTerminalAppVersion) {
      ktLog.i('安装版本和当前版本一样的先修改当前版本名称');
      alerName = oldFilePath + '.1';
      fs.renameSync(oldFilePath, alerName);
    } else {
      if (fs.existsSync(writePath)) {
        ktLog.i(`存在和升级文件相同文件名的文件：${writePath} 删除文件`);
        fs.unlinkSync(writePath);
      }
    }
    ktLog.i('正在升级程序,开始下载AppImage安装包：' + data.newTerminalAppResUrl);
    exec(` wget --timeout=1800 --tries=6 --waitretry=300 -c -P  ${baseDir}/Desktop ${data.newTerminalAppResUrl} `, { timeout: 1000 * 60 * 30 }, (error, stdout, stderr) => {
      if (error) {
        ifUpdateApplication = false;
        ktLog.i('下载文件错误取消升级：' + error);
        try {
          // 文件是否存在
          fs.accessSync(writePath, fs.constants.F_OK);
          fs.unlinkSync(writePath);
        } catch (error) {}
        if (alerName) {
          ktLog.i('下载文件错误取消升级：' + '原文件名称改回去');
          fs.renameSync(alerName, oldFilePath);
          fs.chmodSync(oldFilePath, '777');
        }
        ifUpdateApplication = false;
        return resolve({ code: 2 });
      }
      //安装包全部下载完成
      if (stderr.search('100%') != -1) {
        ktLog.i('文件下载完毕');
        ktLog.i('给新程序赋予777权限');
        fs.chmodSync(writePath, '777');
        ktLog.i('修改开机启动文件');
        let shPath = `${baseDir}/.config/autostart/Startup${name.toUpperCase()}.sh`;
        let desktopFileTargetPath = path.join(`${baseDir}/.config/autostart`, name.toUpperCase() + '.desktop');
        fs.writeFileSync(
          shPath,
          `cd ${baseDir}/Desktop
    ./${data.newTerminalAppVersion}.AppImage &`
        );
        fs.writeFileSync(
          desktopFileTargetPath,
          '[Desktop Entry]\n' +
            '\n' +
            'Type=Application\n' +
            '\n' +
            'Name=' +
            name.toUpperCase() +
            '\n' +
            '\n' +
            'NoDisplay=true\n' +
            '\n' +
            `Exec=${baseDir}/.config/autostart/Startup` +
            name.toUpperCase() +
            '.sh'
        );
        fs.chmodSync(shPath, '777');
        exec(`dpkg -l|grep ${name.toLowerCase()}`, (error, stdout, stderr) => {
          if (stdout.includes(`${name.toLowerCase()}`)) {
            exec(`sudo dpkg --purge ${name.toLowerCase()}`, (error, stdout, stderr) => {
              if (error) {
                ktLog.i('卸载已安装' + name.toLowerCase() + 'deb包错误' + error);
                ifUpdateApplication = false;
                return resolve({ code: 1 });
              }
              ktLog.i('卸载已安装' + name.toLowerCase() + '，deb完成');
              let autostartDesktop = `${baseDir}/.config/autostart/${name.toLowerCase()}.desktop`;
              if (fs.existsSync(autostartDesktop)) {
                fs.unlinkSync(autostartDesktop);
              }
              if (fs.existsSync(alerName)) {
                fs.unlinkSync(alerName);
              }
              ktLog.i('卸载已安装' + name.toLowerCase() + 'deb包成功');
              ktLog.i('升级成功');
              ifUpdateApplication = false;
              return resolve({ code: 1 });
            });
          } else {
            if (alerName) {
              ktLog.i('删除旧程序文件:' + alerName);
              fs.unlinkSync(alerName);
            } else {
              if (fs.existsSync(oldFilePath)) {
                ktLog.i('删除旧程序文件:' + oldFilePath);
                fs.unlinkSync(oldFilePath);
              }
            }
            ktLog.i('升级成功');
            ifUpdateApplication = false;
            return resolve({ code: 1 });
          }
        });
      } else {
        if (alerName) {
          ifUpdateApplication = false;
          ktLog.i('文件未全部下载完成取消升级：' + '原文件名称改回去');
          fs.renameSync(alerName, oldFilePath);
          fs.chmodSync(oldFilePath, '777');
        }
        ifUpdateApplication = false;
        return resolve({ code: 2 });
      }
    });
  });
}
module.exports = {
  linuxUpdateDeb,
  linuxUpdateAppImage,
};
