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