-
Notifications
You must be signed in to change notification settings - Fork 0
/
block-hosts
executable file
·79 lines (59 loc) · 2.24 KB
/
block-hosts
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
#!/usr/bin/env awesome-bash
# vim: ft=sh:
awesome_shell_help <<_HELP_
Usage: $awesome_shell_script_name [-r]
Blocks some unwanted sites from:
https://github.com/StevenBlack/hosts
Entries are written to /etc/hosts
options:
-r, --remove Remove previosly written entries
_HELP_
#awesome-shell ref:403763b
file='/etc/hosts'
if [ ! -r "$file" ];then
fatal "Cannot read information from file: $file"
fi;
required_utility mktemp
remove=0
while [[ $# -gt 0 ]]
do
opt="$1"
shift
case $opt in
-r|--remove)
remove=1
;;
esac
done;
updates_file=$(mktemp 2>/dev/null || mktemp -t hosts)
[ -w "$updates_file" ] || fatal "Cannot create temp file for hosts updates"
silent_exec_with_title "Getting hosts updates from StevenBlack/hosts" "curl -f https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts -o $updates_file"
fatal_if_any_error
entry_count=$(grep -c '^0.0.0.0' "$updates_file")
msg "File contains $entry_count entries"
marker='# https://github.com/StevenBlack/hosts'
marker_start="$marker <start>"
marker_end="$marker <end>"
start_line=$(grep -n "$marker_start" "$file" | head -1 | cut -f1 -d:)
end_line=$(grep -n "$marker_end" "$file" | head -1 | cut -f1 -d:)
awesome_shell_include password
keep_sudo_alive
if [ -n "$start_line" ] && [ -n "$end_line" ];then
msg 'Previous markers have been found. Will need to clean up.'
bak_file="${updates_file}.bak"
sed -e "${start_line},${end_line}d;" "$file" > "$bak_file"
fatal_if_any_error "Cannot create temp backup file"
sudo mv "$bak_file" "$file"
fatal_if_any_error "Cannot produce cleaned up file $file"
msg "Number of lines in $file after cleanup $(wc -l $file)"
fi;
[ $remove -eq 1 ] && exit 0
start_line=$(grep -n "$marker_start" "$file" | head -1 | cut -f1 -d:)
end_line=$(grep -n "$marker_end" "$file" | head -1 | cut -f1 -d:)
[ -z "$start_line" ] && [ -z "$end_line" ]
fatal_if_any_error "StevenBlack/hosts markers should not be present in $file"
echo -e "$marker_start" | sudo tee -a "$file" 1>/dev/null 2>/dev/null
grep '^0.0.0.0' "$updates_file" | sudo tee -a "$file" 1>/dev/null 2>/dev/null
echo -e "$marker_end" | sudo tee -a "$file" 1>/dev/null 2>/dev/null
msg "Final number of lines in $file $(wc -l $file)"
rm "$updates_file"