3 ## open : string -> unit
5 ## Fork xdg-open so we don't block current terminal session when opening
6 ## things like pdf files. For example:
14 ## notify_done : unit -> unit
16 local -r _status_code
="$?"
17 local -r _program
="$1"
19 _timestamp
="$(timestamp)"
20 local -r _msg
="$_timestamp [$_program] done "
21 if [[ "$_status_code" -eq 0 ]]
23 notify-send
-u normal
"$_msg OK: $_status_code"
25 notify-send
-u critical
"$_msg ERROR: $_status_code"
31 local -r usage
='Usage: p [FILE] NAME'
53 BEGIN {_s = tolower(_s)}
55 # TODO fzf/dmenu select instead of searching:
56 /^[a-zA-Z]/ && tolower($1) ~ _s && NF >= 2 {
69 } # TODO What would NF > 4 mean?
71 printf("%d [O] s:\"%s\", e:\"%s\", u:\"%s\"\n", n, s, e, u) > "/dev/stderr"
76 printf("%d [C] s:\"%s\", e:\"%s\", u:\"%s\"\n", n, s, e, u) > "/dev/stderr"
82 printf "%s", ps[n] # XXX Intentionally avoiding newline in the result.
86 printf "[ERROR] Found nothing.\n" > "/dev/stderr"
89 # TODO fzf-select which of the records the user (ahem, me) wants.
90 printf "[WARNING] Found more than one record. Selecting the last one.\n" > "/dev/stderr"
100 ## ws : string -> unit
102 local line search_string0 search_string
105 case "$search_string0" in
107 while read -r line
; do
108 search_string
="${search_string} ${line}"
111 search_string
="$search_string0";;
114 firefox
--search "$search_string"
119 ## d : string -> string list
121 local -r word
=$
(fzf
< /usr
/share
/dict
/words
)
125 ## shell_activity_report : (mon | dow) -> string list
126 shell_activity_report
() {
127 # TODO: optional concrete number output
128 # TODO: optional combinations of granularities: hour, weekday, month, year
135 echo "Usage: $0 [mon|dow]" >&2
139 |
awk -v group_by
="$group_by" '
140 function date2dow(y, m, d, _t, _i) {
142 # y > 1752, 1 <= m <= 12.
145 # https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto%27s_methods
159 _i = int(y + y/4 - y/100 + y/400 + _t[m - 1] + d) % 7
160 _i = _i == 0 ? 7 : _i # Make Sunday last
166 # NOTE: $2 & $3 are specific to oh-my-zsh history output
169 d_fields = split(date, d, "-")
170 t_fields = split(time, t, ":")
171 if (t_fields && d_fields) {
172 # +0 to coerce number from string
177 dow = date2dow(year, month, day)
178 g = group_by == "mon" ? month : dow # dow is default
207 n = group_by == "mon" ? 12 : 7 # dow is default
209 for (gid = 1; gid <= n; gid++) {
210 group = group_by == "mon" ? m[gid] : w[gid]
211 printf "%s\n", group;
212 for (hour=0; hour<24; hour++) {
215 for (i = 1; i <= (c * 100) / max; i++)
223 ## top_commands : unit -> (command:string * count:number * bar:string) list
233 print count[cmd], cmd
240 c = count[NR] = $1 + 0 # + 0 to coerce number from string
246 for (i = 1; i <= NR; i++) {
248 printf "%s %d ", cmd[i], c
249 scaled = (c * 100) / max
250 for (j = 1; j <= scaled; j++)
258 ## Top Disk-Using directories
259 ## tdu : path-string -> (size:number * directory:path-string) list
261 local -r root_path
="$1"
267 # A slight optimization: head can exit before traversing the full input.
270 ## Top Disk-Using Files
271 ## tduf : path-string list -> (size:number * file:path-string) list
273 find "$@" -type f
-printf '%s\t%p\0' \
276 | numfmt
-z --to=iec \
280 # Most-recently modified file system objects
281 ## recent : ?(path-string list) -> path-string list
284 # - %T+ is a GNU extension;
285 # - gawk is able to split records on \0, while awk cannot.
286 find "$@" -printf '%T@ %T+ %p\0' \
287 |
tee >(gawk
-v RS
='\0' 'END { printf("[INFO] Total found: %d\n", NR); }') \
288 |
sort -z -k 1 -n -r \
289 |
head -n "$(stty size | awk 'NR == 1 {print $1 - 5}')" -z \
292 sub("^" $1 " +", "") # Remove epoch time
293 sub("+", " ") # Blank-out the default separator
294 sub("\\.[0-9]+", "") # Remove fractional seconds
299 ## recent_dirs : ?(path-string list) -> path-string list
304 ## recent_files : ?(path-string list) -> path-string list
309 ## pa_def_sink : unit -> string
311 pactl info |
awk '/^Default Sink:/ {print $3}'
314 ## void_pkgs : ?(string) -> json
316 curl
"https://xq-api.voidlinux.org/v1/query/x86_64?q=$1" | jq
'.data'
320 ## man : string -> string
324 # me: end bold, blink and underline
326 # so: begin standout (reverse video)
329 # us: begin underline
332 LESS_TERMCAP_md
=$
'\e[01;30m' \
333 LESS_TERMCAP_me
=$
'\e[0m' \
334 LESS_TERMCAP_so
=$
'\e[01;44;33m' \
335 LESS_TERMCAP_se
=$
'\e[0m' \
336 LESS_TERMCAP_us
=$
'\e[01;33m' \
337 LESS_TERMCAP_ue
=$
'\e[0m' \
342 ## x : string list -> unit
344 cd "$(~/bin/x $@)" ||
kill -INT $$
348 ## hump : unit -> unit
350 ledit
-l "$(stty size | awk '{print $2}')" ocaml $@
354 ## howto : unit -> string
356 cat "$(find ~/arc/doc/HOWTOs -mindepth 1 -maxdepth 1 | sort | fzf)"
360 local -r base_dir
="$1"
364 local -r yt
=youtube-dl
365 local -r id
=$
("$yt" --get-id "$uri")
366 local -r title
=$
("$yt" --get-title "$uri" |
sed 's/[^А-Яа-яA-Za-z0-9._-]/_/g')
367 local -r dir
="${base_dir}/${title}--${id}"
370 cd "$dir" ||
kill -INT $$
372 "$yt" $opts -c --write-all-thumbnails --write-description --write-info-json "$uri"
377 _yt
"${DIR_YOUTUBE_AUDIO}/individual" "$uri" '-f 140'
382 _yt
"${DIR_YOUTUBE_VIDEO}/individual" "$uri"
386 local -r user_type
="$1"
387 local -r user_name
="$2"
389 curl
"https://api.github.com/$user_type/$user_name/repos?page=1&per_page=10000"
393 local -r gh_user_type
="$1"
394 local -r gh_user_name
="$2"
396 local -r gh_dir
="${DIR_GITHUB}/${gh_user_name}"
398 cd "$gh_dir" ||
kill -INT $$
399 gh_fetch_repos
"$gh_user_type" "$gh_user_name" \
400 | jq
--raw-output '.[] | select(.fork | not) | .clone_url' \
406 gh_clone
'users' "$1"
414 gh_username
=$
(echo "$1" |
awk -F / '"$1 == "https" && $3 == github.com" {print $4}')
415 gh_dir
="${DIR_GITHUB}/${gh_username}"
417 cd "$gh_dir" ||
kill -INT $$
422 local -r len
="${1:-79}" # 1st arg or 79.
423 local -r char
="${2:--}" # 2nd arg or a dash.
424 for _
in {1..
"$len"}; do
429 daily_todo_file_template
() {
431 ===============================================================================
433 ===============================================================================
435 -------------------------------------------------------------------------------
437 -------------------------------------------------------------------------------
440 -------------------------------------------------------------------------------
442 -------------------------------------------------------------------------------
445 -------------------------------------------------------------------------------
447 -------------------------------------------------------------------------------
450 -------------------------------------------------------------------------------
452 -------------------------------------------------------------------------------
459 local -r dir
="$DIR_TODO/daily"
460 local -r file="$dir/$date.txt"
465 daily_todo_file_template
> "$file"
467 cd "$DIR_TODO" && "$EDITOR" $EDITOR_ARGS "$file"
471 cd "$DIR_TODO" && "$EDITOR" TODO
474 work_log_template
() {
496 mkdir
-p "$DIR_WORK_LOG"
497 local -r file_work_log_today
="${DIR_WORK_LOG}/daily-$(date +%F).md"
498 if [ ! -f "$file_work_log_today" ]
500 work_log_template
> "$file_work_log_today"
502 vim
-c 'set spell' "$file_work_log_today"
507 mkdir
-p "$DIR_NOTES"
508 vim
-c 'set spell' "$DIR_NOTES/$(date +'%Y_%m_%d--%H_%M_%S%z')--$1.md"
512 # grep's defintion of a line does not include \r, wile awk's does and
513 # which bluetoothctl outputs
514 awk '/^Device +/ {print $2}' \
515 |
xargs -I% sh
-c 'echo info % | bluetoothctl' \
516 |
awk '/^Device |^\t[A-Z][A-Za-z0-9]+: /'
520 echo 'paired-devices' | bluetoothctl | _bt_devs_infos
524 echo 'devices' | bluetoothctl | _bt_devs_infos
528 local -r stderr
="$(mktemp)"
532 $@
2> >(tee "$stderr")
535 0) urgency
='normal';;
536 *) urgency
='critical'
538 notify-send
-u "$urgency" "Job done: $code" "$(cat $stderr)"
546 width = width ? width : 80
547 ch_left = ch_left ? ch_left : "["
548 ch_right = ch_right ? ch_right : "]"
549 ch_blank = ch_blank ? ch_blank : "-"
550 ch_used = ch_used ? ch_used : "|"
560 cur_scaled = num_scale(cur, max, 1, width)
564 lab ? lab " " : "", \
565 num ? cur "/" max " " : "", \
566 pct ? sprintf("%3.0f%% ", cur / max * 100) : "", \
568 for (i=1; i<=width; i++) {
569 c = i <= cur_scaled ? ch_used : ch_blank
572 printf "%s\n", ch_right
575 function num_scale(src_cur, src_max, dst_min, dst_max) {
576 return dst_min + ((src_cur * (dst_max - dst_min)) / src_max)
589 pct = cur / max * 100
590 printf "%s%s %.2f%%", sep, name, pct
599 curl
--silent --show-error --max-time "${1:=1}" 'https://api.ipify.org' 2>&1
605 if which upower
> /dev
/null
614 / battery/ && device["path"] {
615 device["is_battery"] = 1
619 / percentage:/ && device["is_battery"] {
620 device["battery_percentage"] = $2
621 sub("%$", "", device["battery_percentage"])
626 if (device["is_battery"] && device["path"] == "/org/freedesktop/UPower/devices/DisplayDevice")
627 print device["battery_percentage"], 100, "batt"
637 awk -v unit
="$1" '{printf "%s%s\n", unit, $0}'
641 local -r indent_unit
=' '
651 # TODO Bring back seesion and client listing, but per server/socket.
652 printf '%stmux\n' "$indent_unit"
655 # Expecting lines like:
656 # "tmux: server tmux -L pistactl new-session -d -s pistactl"
657 # "tmux: client tmux -L foo"
658 # "tmux: client tmux -Lbar"
659 # "tmux: client tmux"
660 # "tmux: server tmux -L foo -S bar" <-- -S takes precedence
662 # XXX This of course assumes pervasive usage of -L
666 split($0, sides_of_S, "-S")
667 split(sides_of_S[2], words_right_of_S, FS)
669 split($0, sides_of_L, "-L")
670 split(sides_of_L[2], words_right_of_L, FS)
672 if (words_right_of_S[1]) {
673 sock = "path." words_right_of_S[1]
674 } else if (words_right_of_L[1]) {
675 sock = "name." words_right_of_L[1]
686 for (sock in socks) {
687 clients = count["client", sock]
690 printf "<-> %d", clients
698 | indent
"${indent_unit}${indent_unit}"
702 printf '%sprocs by user\n' "${indent_unit}"
711 for (user in count_by_user)
712 print count_by_user[user], total, user
716 | indent
"${indent_unit}${indent_unit}"
722 free |
awk '$1 == "Mem:" {print $3, $2, "mem"}'
723 df ~ |
awk 'NR == 2 {print $3, $3 + $4, "disk"}'
726 | bar_gauge
-v width
=60 -v pct
=1 \
728 | indent
"$indent_unit"
732 printf '%smem by proc\n' "$indent_unit"
734 |
awk -v total
="$(free | awk '$1 == "Mem
:" {print $2; exit}')" '
742 for (proc in by_proc)
743 print by_proc[proc], total, proc
747 | indent
"${indent_unit}${indent_unit}"
751 local _dir temp_input label_file label
753 printf '%sthermal\n' "$indent_unit"
754 for _dir
in /sys
/class
/hwmon
/hwmon
*; do
756 find "$_dir"/ -name 'temp*_input' \
757 |
while read -r temp_input
; do
758 label_file
=${temp_input//_input/_label}
759 if [ -f "$label_file" ]; then
760 label
=$
(< "$label_file")
764 awk -v label
="$label" '{
766 label = sprintf(" (%s)", label)
767 printf("%.2f°C%s\n", $1 / 1000, label)
772 | indent
"$indent_unit"
774 | indent
"${indent_unit}${indent_unit}"
777 #local -r internet_addr=$(internet_addr 0.5)
778 #local -r internet_ptr=$(host -W 1 "$internet_addr" | awk 'NR == 1 {print $NF}' )
780 #echo "${indent_unit}internet"
781 #echo "${indent_unit}${indent_unit}$internet_addr $internet_ptr"
782 echo "${indent_unit}if"
783 (ifconfig
; iwconfig
) 2> /dev
/null \
787 sub(":$", "", device)
790 sub("^ESSID:\"", "", _essid)
791 sub("\"$", "", _essid)
792 essid[device] = _essid
797 /^ / && $1 == "inet" {
802 /^ +Link Quality=[0-9]+\/[0-9]+ +Signal level=/ {
803 split($2, lq_parts_eq, "=")
804 split(lq_parts_eq[2], lq_parts_slash, "/")
805 cur = lq_parts_slash[1]
806 max = lq_parts_slash[2]
807 link[device] = cur / max * 100
812 for (device in address)
813 if (device != "lo") {
816 l = l ? sprintf("%.0f%%", l) : "--"
818 print device, address[device], e, l
823 | indent
"${indent_unit}${indent_unit}"
825 # WARN: ensure: $USER ALL=(ALL) NOPASSWD:/bin/netstat
827 echo "${indent_unit}-->"
829 # TODO Populate pid->cmd dict from `ps -eo pid,comm` and lookup progs there
830 # since netstat -p output comes out truncated.
832 sudo
-n netstat
-tulnp \
833 |
awk -v indent
="${indent_unit}${indent_unit}" '
834 NR > 2 && ((/^tcp/ && proc = $7) || (/^udp/ && proc = $6)) {
837 port = a[split(addr, a, ":")]
838 name = p[split(proc, p, "/")]
840 protocols[protocol] = 1
841 if (!seen[protocol, name, port]++)
842 ports[protocol, name, ++seen[protocol, name]] = port
846 for (protocol in protocols) {
847 printf "%s%s\t", indent, toupper(protocol)
848 for (name in names) {
849 if (n = seen[protocol, name]) {
852 for (i = 1; i <= n; i++) {
853 printf "%s%d", sep, ports[protocol, name, i]
863 echo "${indent_unit}<->"
865 printf '%sTCP\t' "${indent_unit}${indent_unit}"
866 sudo
-n netstat
-tnp \
867 |
awk 'NR > 2 && $6 == "ESTABLISHED" {print $7}' \
868 |
awk '{sub("^[0-9]+/", ""); print}' \
873 # TODO: iptables summary
876 ssh_invalid_by_addr
() {
878 /: Invalid user/ && $5 ~ /^sshd/ {
879 addr=$10 == "port" ? $9 : $10
885 for (addr in by_addr)
886 if ((c = by_addr[addr]) > 1)
887 printf "%d %d %s\n", c, max, addr
891 /var
/log
/auth.log
.1 \
893 | bar_gauge
-v width
="$(stty size | awk '{print $2}')" -v num
=1 -v ch_right
=' ' -v ch_left
=' ' -v ch_blank
=' ' \
897 ssh_invalid_by_day
() {
914 /: Invalid user/ && $5 ~ /^sshd/ {
922 if ((c = by_day[day]) > 1)
923 printf "%d %d %s\n", c, max, day
927 /var
/log
/auth.log
.1 \
929 | bar_gauge
-v width
="$(stty size | awk '{print $2}')" -v num
=1 -v ch_right
=' ' -v ch_left
=' ' -v ch_blank
=' ' \
933 ssh_invalid_by_user
() {
935 /: Invalid user/ && $5 ~ /^sshd/ {
942 for (user in by_user)
943 if ((c = by_user[user]) > 1)
944 printf "%d %d %s\n", c, max, user
948 /var
/log
/auth.log
.1 \
950 | bar_gauge
-v width
="$(stty size | awk '{print $2}')" -v num
=1 -v ch_right
=' ' -v ch_left
=' ' -v ch_blank
=' ' \
958 sub(":$", "", prog[1]) # if there were no [], than : will is left behind
960 }' /var
/log
/syslog
/var
/log
/syslog
.1 \
963 n = split($1, path, "/") # prog may be in path form
971 print count[prog], total, prog
974 | bar_gauge
-v num
=1 -v ch_right
=' ' -v ch_left
=' ' -v ch_blank
=' ' \