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