var fs=require("fs"),exec=require("child_process").exec,WINDOWS="win32"==process.platform||"darwin"==process.platform,_DATA="/data/",_TMP="/tmp/",_BACK="";function rm_file(e){try{fs.unlinkSync(e)}catch(e){}}function mkdir(e){try{fs.mkdirSync(e)}catch(e){}}WINDOWS&&(_DATA="data/",_TMP="tmp/",_BACK="../");var html,log=console.log,express=require("express"),app=express(),server=(mkdir(_TMP+"uploads"),app.use(express.bodyParser({uploadDir:_TMP+"uploads"})),fs.existsSync("./recovery.html")?(html=fs.readFileSync("./recovery.html"),app.get("/",function(e,r){r.end(html)})):(log("*** DEVELOPMENT MODE ***"),app.use(express.static("public",{index:"recovery.html"}))),app.listen(80)),backup_delete_timer=(log("*** ShotMarker RECOVERY ***"),app.get("/restart",function(e,r){r.redirect("/#restarting"),WINDOWS||(log("rebooting..."),exec("sleep 1 && reboot")),setTimeout(function(){process.exit(0)},500)}),0);app.get("/download_backup",function(e,a){log("downloading backup...");var r=(new Date).toDateString().split(" "),i="SM_backup_"+(r[1]+" "+r[2]).replace(" ","_")+".tar";exec("rm -rf "+_TMP+"SM_backup* && cd "+_DATA+" && tar -cf "+_BACK+_TMP+i+" *",function(e,r,t){null==e?(log("  file created, starting download"),a.download(_TMP+i,i)):(log("  backup failed: ",t),a.redirect("back"))}),clearTimeout(backup_delete_timer),backup_delete_timer=setTimeout(function(){log("deleting backup file"),exec("rm -rf "+_TMP+"SM_backup*")},3e4)}),app.post("/restore_backup",function(e,r){log("restoring backup...");var t,e=e.files.tar;e&&0<=e.originalFilename.indexOf(".tar")?(log("  from "+e.path),r.redirect("/#restarting"),t=(t=(t="sleep 2")+" && cd "+_TMP+" && rm -rf tardir && mkdir tardir")+" && tar -xf "+_BACK+e.path+" -C tardir && [ -f tardir/data.txt ]",WINDOWS&&(t+=" && cd "+_BACK),t=t+" && rm -rf "+_DATA+"* && cp -r "+_TMP+"tardir/* "+_DATA,WINDOWS||(t+=" ; sync && sleep 1 && /app/start.sh"),log(t),exec(t),setTimeout(function(){process.exit(0)},500)):(log("  invalid file type"),e&&rm_file(e.path),r.redirect("/#tar_error"))}),app.get("/factory_reset",function(e,r){r.redirect("/#restarting"),log("factory reset");r="rm -rf "+_DATA+"* && sync && sleep 1 && /app/start.sh";log(r),exec(r),setTimeout(function(){process.exit(0)},500)}),app.post("/software_update",function(e,r){log("updating software...");var t,e=e.files.tar;e&&0<=e.originalFilename.indexOf(".tar")?(log("  from "+e.path),WINDOWS?(log("  cannot update software on windows!"),r.redirect("back")):(r.redirect("/#restarting"),t="sleep 2",t=(t+=" && cd "+_TMP)+" && rm -rf tardir && mkdir tardir && tar -xf "+e.path+" -C tardir",log(t=(t=t+" && [ -f tardir/server.js ]"+" && /root/rw_app && rm -rf /app/* && cp -r tardir/* /app/")+" ; /root/ro_app"+" ; sync && sleep 1 && /app/start.sh"),exec(t),setTimeout(function(){process.exit(0)},500))):(log("  invalid file type"),e&&rm_file(e.path),r.redirect("/#tar_error"))});