//!wrt $BSPEC:{"icn":"apps/updater","cpr":"Copyright (C) Windows 96 Team 2023.","dsc":"System Updater","frn":"System Updater","ver":1,"ssy":"gui"}

const{DialogCreator:DialogCreator,Theme:Theme}=w96.ui,{rel:OSRelease,flags:flags,kInfo:kInfo}=w96.sys,{sideloadZip:sideloadZip}=w96.util;let term=this.boxedEnv.term;async function getInstallState(){try{return JSON.parse(await FS.readstr("C:/system/etc/inststate.json"))}catch(t){const e={rootfs:kInfo.rootfsUrl,version:await OSRelease.getVersionString(),installDate:(new Date).toUTCString()};return await FS.writestr("C:/system/etc/inststate.json",JSON.stringify(e,null,4)),e}}async function isUpdateRequired(){try{return(await getInstallState()).version!=await OSRelease.getVersionString()}catch(t){console.error(t)}return!1}class SysUpdApp extends WApplication{constructor(){super()}async main(t){switch(await super.main(t),t.shift(),t[0]){default:this.log("Invalid argument.");break;case"1stboot":await this.checkKernelImage();break;case"check":flags.has("no_update_notifs")||await this.performCheck()}this.terminate()}async checkKernelImage(){try{if(!kutil.sysrom.exists("kernel.js")){this.log("No stored kernel found, downloading...");const t=await fetch(location.origin+"/system/libraries/kernel/sys-base/kernel.js",{cache:"no-store"}).then((t=>t.text()));kutil.sysrom.write("kernel.js",t),this.log("Download complete.")}kutil.sysrom.exists("KLoader.txt")||(this.log("Updating KLoader boot configuration... please wait."),kutil.sysrom.write("KLoader.txt",JSON.stringify({config:{defaultItem:"Win96"},items:[{id:"Win96",file:"kernel.js"}]})),this.log("Update complete."))}catch(t){console.error(t),this.log(new String(t))}}async performCheck(){if(await isUpdateRequired()){const t=this.createWindow({title:"System Update Notification",bodyClass:"sysupd-notif-wnd",body:`\n                    <div class="top">\n                        <div class="winlogo"></div>\n                        <div class="text">\n                            A new OS version is available for your system. It is strongly recommended that you install this update now to stay up-to-date.<br><br>\n                            If you choose to postpone this for any reason, your system may become unstable over time.<br><br>\n                            Any update postponement will last until the next reboot.<br><br>\n                            Version Upgrade: <span class="bold-noaa">${(await getInstallState()).version} -&gt; ${OSRelease.getVersionString()}</span>\n                        </div>\n                    </div>\n                    <div class="bottom">\n                        <button class="w96-button cancel">Notify Me Later</button>\n                        <button class="w96-button accept">Update &amp; Restart</button>\n                    </div>\n                `,controlBoxStyle:"WS_CBX_CLOSE",taskbar:!1,resizable:!1,icon:null,initialHeight:230,initialWidth:432},!1),e=t.getBodyContainer();e.querySelector(".cancel").addEventListener("click",(()=>t.close())),e.querySelector(".accept").addEventListener("click",(async()=>{t.close();const e=DialogCreator.progress("Processing system update, please wait...",{title:"System Updater",icon:await Theme.getIconUrl("apps/updater")});e.wnd.setControlBoxStyle("WS_CBX_NONE");const s=await getInstallState();if(!s.rootfs){const t=DialogCreator.alert("This system cannot be updated with this method.",{icon:"error",title:"System Update Error"});return await t.wait(),void e.close()}localStorage.setItem("ot-update-url",s.rootfs||"/system/images/rootfs/rootfs.zip"),await FS.rm("C:/system/wupd/sys_dl.lock"),await FS.writestr("C:/system/etc/inststate.json",JSON.stringify({...s,version:OSRelease.getVersionString()},null,4)),w96.sys.reboot()})),t.show(),t.center(),await t.wait()}}log(t){term&&term.println(t)}}

return await WApplication.execAsync(new SysUpdApp(), this.boxedEnv.args, this);