/
lmcswitch
executable file
·63 lines (54 loc) · 1.54 KB
/
lmcswitch
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
#!/usr/bin/env php
<?php
function writeln($msg, $error = FALSE) {
$msg = $msg . "\n";
if ($error) {
die($msg);
} else {
echo $msg;
}
}
$environments = array('devel', 'dev2', 'dev3', 'deploy','preprod','prod','off');
if (isset($argv[1])) {
$switch = strtolower($argv[1]);
if (!in_array($switch, $environments)) {
writeln('Invalid environment "' . $switch . '"', TRUE);
}
file_put_contents(getenv("HOME") . "/.lmcenv", "$switch");
} else {
writeln('Missing environment name (' . implode(', ', $environments) . ')', TRUE);
}
$hostsFile = '/etc/hosts';
// backup file
if (!copy($hostsFile, '/tmp/' . basename($hostsFile) . '.bak')) {
writeln('Failed to create backup of ' . $hostsFile, TRUE);
}
$content = file($hostsFile);
$lmc = FALSE;
$env = FALSE;
foreach($content as &$line) {
$line = trim($line);
// lmc start
if ($line === '#### LMC ####') {
$lmc = TRUE;
} elseif ($line === '#### /LMC ####') {
$lmc = FALSE;
} elseif ($lmc) {
if (strlen($line) == 0) {
$env = FALSE;
} elseif (preg_match('/^## (' .implode('|', $environments) . ')$/i', $line, $m)) {
$env = strtolower($m[1]);
} elseif ($env) {
$line = ($env == $switch ? '' : '#') . ltrim($line, '#');
}
if (preg_match('/(\.?jobs\.cz|\.?prace\.cz|\.?hotjobs\.cz|.?lmc\.cz)/i', $line, $m)) {
$line = ($switch!='off' ? '' : '#') . ltrim($line, '#');
}
}
}
if (@file_put_contents($hostsFile, implode("\n", $content) . "\n")) {
system('dscacheutil -flushcache');
writeln('Switched to ' . strtoupper($switch));
} else {
writeln($hostsFile . ' save failed', TRUE);
}