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