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