-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitupdate.js
More file actions
87 lines (77 loc) · 2.47 KB
/
Copy pathgitupdate.js
File metadata and controls
87 lines (77 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
let { exec, execSync } = require('child_process')
let runDirectly = !module.parent
function timeUntilHour(hour) {
if (hour < 0 || hour > 24) throw new Error("Invalid hour format!")
const now = new Date()
const target = new Date(now)
if (now.getHours() >= hour) {
target.setDate(now.getDate() + 1)
}
target.setHours(hour)
target.setMinutes(0)
target.setSeconds(0)
target.setMilliseconds(0)
return target.getTime() - now.getTime()
}
// Copied from lib, but we don't want any internal dependencies for this file
function execute(command){
return new Promise(resolve => {
let isRoot
try {
isRoot = execSync("whoami").toString().toLowerCase().indexOf("root") >= 0
} catch(error) {
isRoot = false
}
exec((isRoot ? "" : "sudo ") + command,
(error, stdout, stderr) => {
if(error){
console.error("execute Error:", error, stdout, stderr)
}
resolve(stdout.toString() + " " + stderr.toString())
})
})
}
async function checkForUpdates(){
let output = await execute('curl -Is -H "Cache-Control: no-cache, no-store;Pragma: no-cache" "http://www.google.com/?$(date +%s)" | head -n 1')
let connected = output.indexOf("200") >= 0
if(!runDirectly){
let nextUpdateTime = connected ? timeUntilHour(2) : 1e4
setTimeout(() => {
checkForUpdates()
}, nextUpdateTime)
}
if(!connected) return
pullAndRestart()
}
async function pullAndRestart() {
await execute("git config pull.ff only")
let output = (await execute("git pull")).toLowerCase()
if(output.indexOf("already up to date") >= 0){
console.log("Already has latest code from git")
} else if(output.indexOf("fatal") >= 0){
console.log("Git pull failed: " + output)
console.log("Deleting empty git objects and retrying")
await execute("find .git/objects/ -type f -size 0 -delete")
pullAndRestart()
} else if(output.indexOf("fast-forward") >= 0 || output.indexOf("files changed") >= 0){
console.log("Has git updates, restarting!")
restartOrbitron()
} else {
console.error("Inconclusive git pull results: ", output)
}
}
// Copied from lib, but we don't want any internal dependencies for this file
async function restartOrbitron(){
let pm2Running = (await execute("ps -ea")).trim().indexOf("pm2") >= 0
if(pm2Running){
execute("pm2 restart all")
} else {
execute("reboot")
}
}
if(runDirectly){
checkForUpdates()
}
module.exports = {
checkForUpdates, pullAndRestart, restartOrbitron, timeUntilHour,
}