forked from viccherubini/get-shit-done
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get-shit-done.php
executable file
·103 lines (81 loc) · 2.49 KB
/
get-shit-done.php
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/env php
<?php
if ( 1 == $argc ) {
exitWithError("usage: " . $argv[0] . " [work | play]");
}
$whoami = trim(`whoami`);
if ( 'root' != strtolower($whoami) ) {
exitWithError("Please run script as root.");
}
$homedir = trim(`cd ~ && pwd`);
$iniLocal = $homedir.'/.config/get-shit-done.ini';
$iniGlobal = __DIR__ . '/sites.ini';
$uname = trim(`uname`);
if ( $uname == 'Linux' ) {
$restartNetworkingCommand = '/etc/init.d/networking restart';
} elseif ( $uname == 'Darwin' ) {
$restartNetworkingCommand = 'dscacheutil -flushcache';
} else {
$message = '"Please contribute DNS cache flush command on GitHub."';
$restartNetworkingCommand = "echo $message";
# Intention isn't to exit, as it still works, but just requires some
# intervention on the user's part.
}
$hostsFile = '/etc/hosts';
$startToken = '## start-gsd';
$endToken = '## end-gsd';
$siteList = iniToArray($iniGlobal);
if (file_exists($iniLocal)) {
$siteList = (array_merge($siteList, iniToArray($iniLocal)));
}
$action = $argv[1];
switch ( $action ) {
case 'work': {
$contents = file_get_contents($hostsFile);
if($contents && strpos($contents, $startToken) !== false && strpos($contents, $endToken) !== false) {
exitWithError("Work mode already set.");
}
$fh = fopen($hostsFile, 'a');
if ( false === $fh ) {
exitWithError("Failed to open the hosts file.");
}
fwrite($fh, $startToken . PHP_EOL);
foreach ( $siteList as $site ) {
fwrite($fh, "127.0.0.1\t{$site}" . PHP_EOL);
fwrite($fh, "127.0.0.1\twww.{$site}" . PHP_EOL);
}
fwrite($fh, $endToken . PHP_EOL);
fclose($fh);
shell_exec($restartNetworkingCommand);
break;
}
case 'play': {
$hostContents = file($hostsFile);
if ( false === $hostContents ) {
exitWithError("Failed to open the hosts file.");
}
$startIndex = -1;
for ( $i=0; $i<count($hostContents); $i++ ) {
if ( trim($hostContents[$i]) == $startToken ) {
$startIndex = $i;
}
}
if ( $startIndex > -1 ) {
$hostContents = array_slice($hostContents, 0, $startIndex);
file_put_contents($hostsFile, $hostContents);
shell_exec($restartNetworkingCommand);
}
break;
}
default: {
exitWithError("usage: " . $argv[0] . " [work | play]");
}
}
function exitWithError($error) {
fwrite(STDERR, $error . PHP_EOL);
exit(1);
}
function iniToArray($iniFile) {
$iniContents = parse_ini_file($iniFile);
return array_map('trim', explode(',', $iniContents["sites"]));
}