8c0a35104731f042c61a6d489e2fbdf949092606
[khome.git] / home / lib / login_functions.sh
1 #
2
3 d() {
4 local -r word=$(fzf < /usr/share/dict/words)
5 dict "$word"
6 }
7
8 shell_activity_report() {
9 # TODO: optional concrete number output
10 # TODO: optional combinations of granularities: hour, weekday, month, year
11 local group_by="$1"
12 case "$group_by" in
13 'mon') ;;
14 'dow') ;;
15 '') group_by='dow';;
16 *)
17 echo "Usage: $0 [mon|dow]" >&2
18 kill -INT $$
19 esac
20 history \
21 | awk -v group_by="$group_by" '
22 function date2dow(y, m, d, _t, _i) {
23 # Contract:
24 # y > 1752, 1 <= m <= 12.
25 # Source:
26 # Sakamoto`s methods
27 # https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto%27s_methods
28 _t[ 0] = 0
29 _t[ 1] = 3
30 _t[ 2] = 2
31 _t[ 3] = 5
32 _t[ 4] = 0
33 _t[ 5] = 3
34 _t[ 6] = 5
35 _t[ 7] = 1
36 _t[ 8] = 4
37 _t[ 9] = 6
38 _t[10] = 2
39 _t[11] = 4
40 y -= m < 3
41 _i = int(y + y/4 - y/100 + y/400 + _t[m - 1] + d) % 7
42 _i = _i == 0 ? 7 : _i # Make Sunday last
43 return _i
44
45 }
46
47 {
48 # NOTE: $2 & $3 are specific to oh-my-zsh history output
49 date = $2
50 time = $3
51 d_fields = split(date, d, "-")
52 t_fields = split(time, t, ":")
53 if (t_fields && d_fields) {
54 # +0 to coerce number from string
55 year = d[1] + 0
56 month = d[2] + 0
57 day = d[3] + 0
58 hour = t[1] + 0
59 dow = date2dow(year, month, day)
60 g = group_by == "mon" ? month : dow # dow is default
61 c = count[g, hour]++
62 }
63 if (c > max)
64 max = c
65 }
66
67 END {
68 w[1] = "Monday"
69 w[2] = "Tuesday"
70 w[3] = "Wednesday"
71 w[4] = "Thursday"
72 w[5] = "Friday"
73 w[6] = "Saturday"
74 w[7] = "Sunday"
75
76 m[ 1] = "January"
77 m[ 2] = "February"
78 m[ 3] = "March"
79 m[ 4] = "April"
80 m[ 5] = "May"
81 m[ 6] = "June"
82 m[ 7] = "July"
83 m[ 8] = "August"
84 m[ 9] = "September"
85 m[10] = "October"
86 m[11] = "November"
87 m[12] = "December"
88
89 n = group_by == "mon" ? 12 : 7 # dow is default
90
91 for (gid = 1; gid <= n; gid++) {
92 group = group_by == "mon" ? m[gid] : w[gid]
93 printf "%s\n", group;
94 for (hour=0; hour<24; hour++) {
95 c = count[gid, hour]
96 printf " %2d ", hour
97 for (i = 1; i <= (c * 100) / max; i++)
98 printf "|"
99 printf "\n"
100 }
101 }
102 }'
103 }
104
105 top_commands() {
106 history \
107 | awk '
108 {
109 count[$4]++
110 }
111
112 END {
113 for (cmd in count)
114 print count[cmd], cmd
115 }' \
116 | sort -n -r -k 1 \
117 | head -50 \
118 | awk '
119 {
120 cmd[NR] = $2
121 c = count[NR] = $1 + 0 # + 0 to coerce number from string
122 if (c > max)
123 max = c
124 }
125
126 END {
127 for (i = 1; i <= NR; i++) {
128 c = count[i]
129 printf "%s %d ", cmd[i], c
130 scaled = (c * 100) / max
131 for (j = 1; j <= scaled; j++)
132 printf "|"
133 printf "\n"
134 }
135 }' \
136 | column -t
137 }
138
139 # Top Disk-Using directories
140 # TODO: Consider using numfmt instead of awk
141 tdu() {
142 du "$1" \
143 | sort -n -k 1 \
144 | tail -50 \
145 | awk '
146 {
147 size = $1
148 path = $0
149 sub("^" $1 "\t+", "", path)
150 gb = size / 1024 / 1024
151 printf("%f\t%s\n", gb, path)
152 }'
153 }
154
155 # Top Disk-Using Files
156 tduf() {
157 find "$1" -type f -printf '%s\t%p\0' \
158 | sort -z -n -k 1 \
159 | tail -z -n 50 \
160 | gawk -v RS='\0' '
161 {
162 size = $1
163 path = $0
164 sub("^" $1 "\t+", "", path)
165 gb = size / 1024 / 1024 / 1024
166 printf("%f\t%s\n", gb, path)
167 }'
168 }
169
170 # Most-recently modified file system objects
171 recent() {
172 # NOTES:
173 # - intentionally not quoting the parameters, so that some can be ignored
174 # if not passed, rather than be passed to find as an empty string;
175 # - %T+ is a GNU extension;
176 # - gawk is able to split records on \0, while awk cannot.
177 find $@ -printf '%T@ %T+ %p\0' \
178 | tee >(gawk -v RS='\0' 'END { printf("[INFO] Total found: %d\n", NR); }') \
179 | sort -z -k 1 -n -r \
180 | head -n "$(stty size | awk 'NR == 1 {print $1 - 5}')" -z \
181 | gawk -v RS='\0' '
182 {
183 sub("^" $1 " +", "") # Remove epoch time
184 sub("+", " ") # Blank-out the default separator
185 sub("\\.[0-9]+", "") # Remove fractional seconds
186 print
187 }'
188 }
189
190 recent_dirs() {
191 recent "$1" -type d
192 }
193
194 recent_files() {
195 recent "$1" -type f
196 }
197
198 pa_def_sink() {
199 pactl info | awk '/^Default Sink:/ {print $3}'
200 }
201
202 void_pkgs() {
203 curl "https://xq-api.voidlinux.org/v1/query/x86_64?q=$1" | jq '.data'
204 }
205
206 # Colorful man
207 man() {
208 # mb: begin blink
209 # md: begin bold
210 # me: end bold, blink and underline
211 #
212 # so: begin standout (reverse video)
213 # se: end standout
214 #
215 # us: begin underline
216 # ue: end underline
217
218 LESS_TERMCAP_md=$'\e[01;30m' \
219 LESS_TERMCAP_me=$'\e[0m' \
220 LESS_TERMCAP_so=$'\e[01;44;33m' \
221 LESS_TERMCAP_se=$'\e[0m' \
222 LESS_TERMCAP_us=$'\e[01;33m' \
223 LESS_TERMCAP_ue=$'\e[0m' \
224 command man "$@"
225 }
226
227 experiment() {
228 cd "$(~/bin/experiment $@)" || kill -INT $$
229 }
230
231 hump() {
232 ledit -l "$(stty size | awk '{print $2}')" ocaml $@
233 }
234
235 howto() {
236 cat "$(find ~/arc/doc/HOWTOs -mindepth 1 -maxdepth 1 | sort | fzf)"
237 }
238
239 _yt() {
240 local -r base_dir="$1"
241 local -r uri="$2"
242 local -r opts="$3"
243
244 local -r id=$(youtube-dlc --get-id "$uri")
245 local -r title=$(youtube-dlc --get-title "$uri" | sed 's/[^A-Za-z0-9._-]/_/g')
246 local -r dir="${base_dir}/${title}--${id}"
247
248 mkdir -p "$dir"
249 cd "$dir" || kill -INT $$
250 echo "$uri" > 'uri'
251 youtube-dlc $opts -c --write-description --write-info-json "$uri"
252 }
253
254 yt_audio() {
255 local -r uri="$1"
256 _yt "${DIR_YOUTUBE_AUDIO}/individual" "$uri" '-f 140'
257 }
258
259 yt_video() {
260 local -r uri="$1"
261 _yt "${DIR_YOUTUBE_VIDEO}/individual" "$uri"
262 }
263
264 gh_fetch_repos() {
265 curl "https://api.github.com/$1/$2/repos?page=1&per_page=10000"
266 }
267
268 gh_clone() {
269 local -r gh_user_type="$1"
270 local -r gh_user_name="$2"
271
272 local -r gh_dir="${DIR_GITHUB}/${gh_user_name}"
273 mkdir -p "$gh_dir"
274 cd "$gh_dir" || kill -INT $$
275 gh_fetch_repos "$gh_user_type" "$gh_user_name" \
276 | jq --raw-output '.[] | select(.fork | not) | .git_url' \
277 | parallel -j 25 \
278 git clone {}
279 }
280
281 gh_clone_user() {
282 gh_clone 'users' "$1"
283 }
284
285 gh_clone_org() {
286 gh_clone 'orgs' "$1"
287 }
288
289 gh_clone_repo() {
290 gh_username=$(echo "$1" | awk -F / '"$1 == "https" && $3 == github.com" {print $4}')
291 gh_dir="${DIR_GITHUB}/${gh_username}"
292 mkdir -p "$gh_dir"
293 cd "$gh_dir" || kill -INT $$
294 git clone "$1"
295 }
296
297 work_log_template() {
298 cat << EOF
299 $(date '+%F %A')
300 ==========
301
302 Morning report
303 --------------
304
305 ### Prev
306
307 ### Curr
308
309 ### Next
310
311 ### Blockers
312
313 Day's notes
314 -----------
315 EOF
316 }
317
318 work_log() {
319 mkdir -p "$DIR_WORK_LOG"
320 local -r file_work_log_today="${DIR_WORK_LOG}/$(date +%F).md"
321 if [ ! -f "$file_work_log_today" ]
322 then
323 work_log_template > "$file_work_log_today"
324 fi
325 vim -c 'set spell' "$file_work_log_today"
326
327 }
328
329 note() {
330 mkdir -p "$DIR_NOTES"
331 vim -c 'set spell' "$DIR_NOTES/$(date +'%Y_%m_%d--%H_%M_%S%z')--$1.md"
332 }
333
334 weather() {
335 local _weather_location
336 case "$1" in
337 '') _weather_location="$WEATHER_LOCATION";;
338 *) _weather_location="$1"
339 esac
340 curl "http://wttr.in/$_weather_location?format=v2"
341 }
342
343 _bt_devs_infos() {
344 # grep's defintion of a line does not include \r, wile awk's does and
345 # which bluetoothctl outputs
346 awk '/^Device +/ {print $2}' \
347 | xargs -I% sh -c 'echo info % | bluetoothctl' \
348 | awk '/^Device |^\t[A-Z][A-Za-z0-9]+: /'
349 }
350
351 bt_devs_paired() {
352 echo 'paired-devices' | bluetoothctl | _bt_devs_infos
353 }
354
355 bt_devs() {
356 echo 'devices' | bluetoothctl | _bt_devs_infos
357 }
358
359 run() {
360 local -r stderr="$(mktemp)"
361
362 local code urgency
363
364 $@ 2> >(tee "$stderr")
365 code="$?"
366 case "$code" in
367 0) urgency='normal';;
368 *) urgency='critical'
369 esac
370 notify-send -u "$urgency" "Job done: $code" "$(cat $stderr)"
371 rm "$stderr"
372 }
373
374 bar_gauge() {
375 awk "$@" '
376 BEGIN {
377 # CLI options
378 width = width ? width : 80
379 ch_left = ch_left ? ch_left : "["
380 ch_right = ch_right ? ch_right : "]"
381 ch_blank = ch_blank ? ch_blank : "-"
382 ch_used = ch_used ? ch_used : "|"
383 num = num ? 1 : 0
384 pct = pct ? 1 : 0
385 }
386
387 {
388 cur = $1
389 max = $2
390 lab = $3
391
392 cur_scaled = num_scale(cur, max, 1, width)
393
394 printf \
395 "%s%s%s%s", \
396 lab ? lab " " : "", \
397 num ? cur "/" max " " : "", \
398 pct ? sprintf("%3.0f%% ", cur / max * 100) : "", \
399 ch_left
400 for (i=1; i<=width; i++) {
401 c = i <= cur_scaled ? ch_used : ch_blank
402 printf "%s", c
403 }
404 printf "%s\n", ch_right
405 }
406
407 function num_scale(src_cur, src_max, dst_min, dst_max) {
408 return dst_min + ((src_cur * (dst_max - dst_min)) / src_max)
409 }
410 '
411 }
412
413 flat_top_5() {
414 sort -n -k 1 -r \
415 | head -5 \
416 | awk '
417 {
418 cur = $1
419 max = $2
420 name = $3
421 pct = cur / max * 100
422 printf "%s%s %.2f%%", sep, name, pct
423 sep = ", "
424 }
425
426 END {printf "\n"}
427 '
428 }
429
430 internet_addr() {
431 curl --silent --show-error --max-time "${1:=1}" 'https://api.ipify.org' 2>&1
432 }
433
434 status_batt() {
435 case "$(uname)" in
436 'Linux')
437 if which upower > /dev/null
438 then
439 upower --dump \
440 | awk '
441 /^Device:[ \t]+/ {
442 device["path"] = $2
443 next
444 }
445
446 / battery/ && device["path"] {
447 device["is_battery"] = 1
448 next
449 }
450
451 / percentage:/ && device["is_battery"] {
452 device["battery_percentage"] = $2
453 sub("%$", "", device["battery_percentage"])
454 next
455 }
456
457 /^$/ {
458 if (device["is_battery"] && device["path"] == "/org/freedesktop/UPower/devices/DisplayDevice")
459 print device["battery_percentage"], 100, "batt"
460 delete device
461 }
462 '
463 fi
464 ;;
465 esac
466 }
467
468 indent() {
469 awk -v unit="$1" '{printf "%s%s\n", unit, $0}'
470 }
471
472 status() {
473 local -r indent_unit=' '
474
475 uname -srvmo
476 hostname | figlet
477 uptime
478
479 echo
480
481 echo 'accounting'
482
483 printf '%stmux\n%ssessions %d, clients %d\n' \
484 "$indent_unit" \
485 "${indent_unit}${indent_unit}" \
486 "$(tmux list-sessions 2> /dev/null | wc -l)" \
487 "$(tmux list-clients 2> /dev/null | wc -l)"
488
489 echo
490
491 printf '%sprocs by user\n' "${indent_unit}"
492 ps -eo user \
493 | awk '
494 NR > 1 {
495 count_by_user[$1]++
496 total++
497 }
498
499 END {
500 for (user in count_by_user)
501 print count_by_user[user], total, user
502 }
503 ' \
504 | flat_top_5 \
505 | indent "${indent_unit}${indent_unit}"
506
507 echo
508
509 echo 'resources'
510 (
511 free | awk '$1 == "Mem:" {print $3, $2, "mem"}'
512 df ~ | awk 'NR == 2 {print $3, $3 + $4, "disk"}'
513 status_batt
514 ) \
515 | bar_gauge -v width=60 -v pct=1 \
516 | column -t \
517 | indent "$indent_unit"
518
519 echo
520
521 printf '%smem by proc\n' "$indent_unit"
522 ps -eo rss,cmd \
523 | awk -v total="$(free | awk '$1 == "Mem:" {print $2; exit}')" '
524 NR > 1 {
525 rss = $1
526 cmd = $2
527 n = split(cmd, path, "/") # _may_ be a path
528 proc = path[n]
529 by_proc[proc] += rss
530 }
531
532 END {
533 for (proc in by_proc)
534 print by_proc[proc], total, proc
535 }
536 ' \
537 | flat_top_5 \
538 | indent "${indent_unit}${indent_unit}"
539
540 echo
541
542 printf '%sthermal\n' "$indent_unit"
543 for _dir in /sys/class/thermal/thermal_zone*
544 do
545 printf '%s %.2f C\n' \
546 $(cat "$_dir"/type) \
547 $(( $(cat "$_dir"/temp) / 1000 ))
548 done \
549 | column -t \
550 | indent "${indent_unit}${indent_unit}"
551
552 echo 'net'
553 local -r internet_addr=$(internet_addr 0.5)
554 local -r internet_ptr=$(host -W 1 "$internet_addr" | awk 'NR == 1 {print $NF}' )
555
556 echo "${indent_unit}internet"
557 echo "${indent_unit}${indent_unit}$internet_addr $internet_ptr"
558 echo "${indent_unit}if"
559 (ifconfig; iwconfig) 2> /dev/null \
560 | awk '
561 /^[^ ]/ {
562 device = $1
563 sub(":$", "", device)
564 if ($4 ~ "ESSID:") {
565 _essid = $4
566 sub("^ESSID:\"", "", _essid)
567 sub("\"$", "", _essid)
568 essid[device] = _essid
569 }
570 next
571 }
572
573 /^ / && $1 == "inet" {
574 address[device] = $2
575 next
576 }
577
578 /^ +Link Quality=[0-9]+\/[0-9]+ +Signal level=/ {
579 split($2, lq_parts_eq, "=")
580 split(lq_parts_eq[2], lq_parts_slash, "/")
581 cur = lq_parts_slash[1]
582 max = lq_parts_slash[2]
583 link[device] = cur / max * 100
584 next
585 }
586
587 END {
588 for (device in address)
589 if (device != "lo") {
590 l = link[device]
591 e = essid[device]
592 l = l ? sprintf("%.0f%%", l) : "--"
593 e = e ? e : "--"
594 print device, address[device], e, l
595 }
596 }
597 ' \
598 | column -t \
599 | indent "${indent_unit}${indent_unit}"
600
601 # WARN: ensure: $USER ALL=(ALL) NOPASSWD:/bin/netstat
602
603 echo "${indent_unit}-->"
604
605 sudo -n netstat -tulnp \
606 | awk -v indent="${indent_unit}${indent_unit}" '
607 NR > 2 && ((/^tcp/ && proc = $7) || (/^udp/ && proc = $6)) {
608 protocol = $1
609 addr = $4
610 port = a[split(addr, a, ":")]
611 name = p[split(proc, p, "/")]
612 names[name] = 1
613 protocols[protocol] = 1
614 if (!seen[protocol, name, port]++)
615 ports[protocol, name, ++seen[protocol, name]] = port
616 }
617
618 END {
619 for (protocol in protocols) {
620 printf "%s%s\t", indent, toupper(protocol)
621 for (name in names) {
622 if (n = seen[protocol, name]) {
623 sep = ""
624 printf "%s:", name
625 for (i = 1; i <= n; i++) {
626 printf "%s%d", sep, ports[protocol, name, i]
627 sep = ","
628 }
629 printf " "
630 }
631 }
632 printf "\n"
633 }
634 }'
635
636 echo "${indent_unit}<->"
637
638 printf '%sTCP: ' "${indent_unit}${indent_unit}"
639 sudo -n netstat -tnp \
640 | awk 'NR > 2 && $6 == "ESTABLISHED" {print $7}' \
641 | awk -F/ '{print $2}' \
642 | sort -u \
643 | xargs \
644 | column -t
645
646 # TODO: iptables summary
647 }
648
649 ssh_invalid_attempts_from() {
650 awk '
651 /: Invalid user/ && $5 ~ /^sshd/ {
652 u=$8
653 addr=$10 == "port" ? $9 : $10
654 max++
655 curr[addr]++
656 }
657
658 END {
659 for (addr in curr)
660 if ((c = curr[addr]) > 1)
661 print c, max, addr
662 }
663 ' \
664 /var/log/auth.log \
665 /var/log/auth.log.1 \
666 | sort -n -k 1 \
667 | bar_gauge -v width="$(stty size | awk '{print $2}')" -v num=1 -v ch_right=' ' -v ch_left=' ' -v ch_blank=' ' \
668 | column -t
669 }
670
671 loggers() {
672 awk '
673 {
674 split($5, prog, "[")
675 sub(":$", "", prog[1]) # if there were no [], than : will is left behind
676 print prog[1]
677 }' /var/log/syslog /var/log/syslog.1 \
678 | awk '
679 {
680 n = split($1, path, "/") # prog may be in path form
681 prog = path[n]
682 total++
683 count[prog]++
684 }
685
686 END {
687 for (prog in count)
688 print count[prog], total, prog
689 }' \
690 | sort -n -k 1 \
691 | bar_gauge -v num=1 -v ch_right=' ' -v ch_left=' ' -v ch_blank=' ' \
692 | column -t
693 }
This page took 0.141133 seconds and 3 git commands to generate.