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 local -r timestamp
="$(date --iso-8601=ns)"
101 local -r dir
="$HOME"/dl
/adhoc
/"$timestamp"
102 local -r url_file_path
="${dir}/url"
105 touch "$url_file_path"
110 ## ws : string -> unit
112 local line search_string0 search_string
115 case "$search_string0" in
117 while read -r line
; do
118 search_string
="${search_string} ${line}"
121 search_string
="$search_string0";;
124 firefox
--search "$search_string"
129 ## d : string -> string list
131 local -r word
=$
(fzf
< /usr
/share
/dict
/words
)
135 ## shell_activity_report : (mon | dow) -> string list
136 shell_activity_report
() {
137 # TODO: optional concrete number output
138 # TODO: optional combinations of granularities: hour, weekday, month, year
145 echo "Usage: $0 [mon|dow]" >&2
149 |
awk -v group_by
="$group_by" '
150 function date2dow(y, m, d, _t, _i) {
152 # y > 1752, 1 <= m <= 12.
155 # https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto%27s_methods
169 _i = int(y + y/4 - y/100 + y/400 + _t[m - 1] + d) % 7
170 _i = _i == 0 ? 7 : _i # Make Sunday last
176 # NOTE: $2 & $3 are specific to oh-my-zsh history output
179 d_fields = split(date, d, "-")
180 t_fields = split(time, t, ":")
181 if (t_fields && d_fields) {
182 # +0 to coerce number from string
187 dow = date2dow(year, month, day)
188 g = group_by == "mon" ? month : dow # dow is default
217 n = group_by == "mon" ? 12 : 7 # dow is default
219 for (gid = 1; gid <= n; gid++) {
220 group = group_by == "mon" ? m[gid] : w[gid]
221 printf "%s\n", group;
222 for (hour=0; hour<24; hour++) {
225 for (i = 1; i <= (c * 100) / max; i++)
233 ## top_commands : unit -> (command:string * count:number * bar:string) list
243 print count[cmd], cmd
250 c = count[NR] = $1 + 0 # + 0 to coerce number from string
256 for (i = 1; i <= NR; i++) {
258 printf "%s %d ", cmd[i], c
259 scaled = (c * 100) / max
260 for (j = 1; j <= scaled; j++)
268 ## Top Disk-Using directories
269 ## tdu : path-string -> (size:number * directory:path-string) list
271 local -r root_path
="$1"
277 # A slight optimization: head can exit before traversing the full input.
280 ## Top Disk-Using Files
281 ## tduf : path-string list -> (size:number * file:path-string) list
283 find "$@" -type f
-printf '%s\t%p\0' \
286 | numfmt
-z --to=iec \
290 # Most-recently modified file system objects
291 ## recent : ?(path-string list) -> path-string list
294 # - %T+ is a GNU extension;
295 # - gawk is able to split records on \0, while awk cannot.
296 find "$@" -printf '%T@ %T+ %p\0' \
297 |
tee >(gawk
-v RS
='\0' 'END { printf("[INFO] Total found: %d\n", NR); }') \
298 |
sort -z -k 1 -n -r \
299 |
head -n "$(stty size | awk 'NR == 1 {print $1 - 5}')" -z \
302 sub("^" $1 " +", "") # Remove epoch time
303 sub("+", " ") # Blank-out the default separator
304 sub("\\.[0-9]+", "") # Remove fractional seconds
309 ## recent_dirs : ?(path-string list) -> path-string list
314 ## recent_files : ?(path-string list) -> path-string list
319 ## pa_def_sink : unit -> string
321 pactl info |
awk '/^Default Sink:/ {print $3}'
324 ## void_pkgs : ?(string) -> json
326 curl
"https://xq-api.voidlinux.org/v1/query/x86_64?q=$1" | jq
'.data'
330 ## man : string -> string
334 # me: end bold, blink and underline
336 # so: begin standout (reverse video)
339 # us: begin underline
342 LESS_TERMCAP_md
=$
'\e[01;30m' \
343 LESS_TERMCAP_me
=$
'\e[0m' \
344 LESS_TERMCAP_so
=$
'\e[01;44;33m' \
345 LESS_TERMCAP_se
=$
'\e[0m' \
346 LESS_TERMCAP_us
=$
'\e[01;33m' \
347 LESS_TERMCAP_ue
=$
'\e[0m' \
352 ## x : string list -> unit
354 cd "$(~/bin/x $@)" ||
kill -INT $$
358 ## hump : unit -> unit
360 ledit
-l "$(stty size | awk '{print $2}')" ocaml $@
364 ## howto : unit -> string
366 cat "$(find ~/arc/doc/HOWTOs -mindepth 1 -maxdepth 1 | sort | fzf)"
370 local -r base_dir
="$1"
374 local -r yt
=youtube-dl
375 local -r id
=$
("$yt" --get-id "$uri")
376 local -r title
=$
("$yt" --get-title "$uri" |
sed 's/[^А-Яа-яA-Za-z0-9._-]/_/g')
377 local -r dir
="${base_dir}/${title}--${id}"
380 cd "$dir" ||
kill -INT $$
382 "$yt" $opts -c --write-all-thumbnails --write-description --write-info-json "$uri"
387 _yt
"${DIR_YOUTUBE_AUDIO}/individual" "$uri" '-f 140'
392 _yt
"${DIR_YOUTUBE_VIDEO}/individual" "$uri"
396 local -r user_type
="$1"
397 local -r user_name
="$2"
399 curl
"https://api.github.com/$user_type/$user_name/repos?page=1&per_page=10000"
403 local -r gh_user_type
="$1"
404 local -r gh_user_name
="$2"
406 local -r gh_dir
="${DIR_GITHUB}/${gh_user_name}"
408 cd "$gh_dir" ||
kill -INT $$
409 gh_fetch_repos
"$gh_user_type" "$gh_user_name" \
410 | jq
--raw-output '.[] | select(.fork | not) | .clone_url' \
416 gh_clone
'users' "$1"
424 gh_username
=$
(echo "$1" |
awk -F / '"$1 == "https" && $3 == github.com" {print $4}')
425 gh_dir
="${DIR_GITHUB}/${gh_username}"
427 cd "$gh_dir" ||
kill -INT $$
432 local -r len
="${1:-79}" # 1st arg or 79.
433 local -r char
="${2:--}" # 2nd arg or a dash.
434 for _
in {1..
"$len"}; do
439 daily_todo_file_template
() {
441 ===============================================================================
443 ===============================================================================
445 -------------------------------------------------------------------------------
447 -------------------------------------------------------------------------------
450 -------------------------------------------------------------------------------
452 -------------------------------------------------------------------------------
455 -------------------------------------------------------------------------------
457 -------------------------------------------------------------------------------
460 -------------------------------------------------------------------------------
462 -------------------------------------------------------------------------------
469 local -r dir
="$DIR_TODO/daily"
470 local -r file="$dir/$date.txt"
475 daily_todo_file_template
> "$file"
477 cd "$DIR_TODO" && "$EDITOR" $EDITOR_ARGS "$file"
481 cd "$DIR_TODO" && "$EDITOR" TODO
484 work_log_template
() {
506 mkdir
-p "$DIR_WORK_LOG"
507 local -r file_work_log_today
="${DIR_WORK_LOG}/daily-$(date +%F).md"
508 if [ ! -f "$file_work_log_today" ]
510 work_log_template
> "$file_work_log_today"
512 vim
-c 'set spell' "$file_work_log_today"
517 mkdir
-p "$DIR_NOTES"
518 vim
-c 'set spell' "$DIR_NOTES/$(date +'%Y_%m_%d--%H_%M_%S%z')--$1.md"
522 # grep's defintion of a line does not include \r, wile awk's does and
523 # which bluetoothctl outputs
524 awk '/^Device +/ {print $2}' \
525 |
xargs -I% sh
-c 'echo info % | bluetoothctl' \
526 |
awk '/^Device |^\t[A-Z][A-Za-z0-9]+: /'
530 echo 'paired-devices' | bluetoothctl | _bt_devs_infos
534 echo 'devices' | bluetoothctl | _bt_devs_infos
538 local -r stderr
="$(mktemp)"
542 $@
2> >(tee "$stderr")
545 0) urgency
='normal';;
546 *) urgency
='critical'
548 notify-send
-u "$urgency" "Job done: $code" "$(cat $stderr)"
556 width = width ? width : 80
557 ch_left = ch_left ? ch_left : "["
558 ch_right = ch_right ? ch_right : "]"
559 ch_blank = ch_blank ? ch_blank : "-"
560 ch_used = ch_used ? ch_used : "|"
570 cur_scaled = num_scale(cur, max, 1, width)
574 lab ? lab " " : "", \
575 num ? cur "/" max " " : "", \
576 pct ? sprintf("%3.0f%% ", cur / max * 100) : "", \
578 for (i=1; i<=width; i++) {
579 c = i <= cur_scaled ? ch_used : ch_blank
582 printf "%s\n", ch_right
585 function num_scale(src_cur, src_max, dst_min, dst_max) {
586 return dst_min + ((src_cur * (dst_max - dst_min)) / src_max)
599 pct = cur / max * 100
600 printf "%s%s %.2f%%", sep, name, pct
609 curl
--silent --show-error --max-time "${1:=1}" 'https://api.ipify.org' 2>&1
615 if which upower
> /dev
/null
624 / battery/ && device["path"] {
625 device["is_battery"] = 1
629 / percentage:/ && device["is_battery"] {
630 device["battery_percentage"] = $2
631 sub("%$", "", device["battery_percentage"])
636 if (device["is_battery"] && device["path"] == "/org/freedesktop/UPower/devices/DisplayDevice")
637 print device["battery_percentage"], 100, "batt"
647 awk -v unit
="$1" '{printf "%s%s\n", unit, $0}'
651 local -r indent_unit
=' '
661 # TODO Bring back seesion and client listing, but per server/socket.
662 printf '%stmux\n' "$indent_unit"
665 # Expecting lines like:
666 # "tmux: server tmux -L pistactl new-session -d -s pistactl"
667 # "tmux: client tmux -L foo"
668 # "tmux: client tmux -Lbar"
669 # "tmux: client tmux"
670 # "tmux: server tmux -L foo -S bar" <-- -S takes precedence
672 # XXX This of course assumes pervasive usage of -L
676 split($0, sides_of_S, "-S")
677 split(sides_of_S[2], words_right_of_S, FS)
679 split($0, sides_of_L, "-L")
680 split(sides_of_L[2], words_right_of_L, FS)
682 if (words_right_of_S[1]) {
683 sock = "path." words_right_of_S[1]
684 } else if (words_right_of_L[1]) {
685 sock = "name." words_right_of_L[1]
696 for (sock in socks) {
697 clients = count["client", sock]
700 printf "<-> %d", clients
708 | indent
"${indent_unit}${indent_unit}"
712 printf '%sprocs by user\n' "${indent_unit}"
721 for (user in count_by_user)
722 print count_by_user[user], total, user
726 | indent
"${indent_unit}${indent_unit}"
732 free |
awk '$1 == "Mem:" {print $3, $2, "mem"}'
733 df ~ |
awk 'NR == 2 {print $3, $3 + $4, "disk"}'
736 | bar_gauge
-v width
=60 -v pct
=1 \
738 | indent
"$indent_unit"
742 printf '%smem by proc\n' "$indent_unit"
744 |
awk -v total
="$(free | awk '$1 == "Mem
:" {print $2; exit}')" '
752 for (proc in by_proc)
753 print by_proc[proc], total, proc
757 | indent
"${indent_unit}${indent_unit}"
761 local _dir temp_input label_file label
763 printf '%sthermal\n' "$indent_unit"
764 for _dir
in /sys
/class
/hwmon
/hwmon
*; do
766 find "$_dir"/ -name 'temp*_input' \
767 |
while read -r temp_input
; do
768 label_file
=${temp_input//_input/_label}
769 if [ -f "$label_file" ]; then
770 label
=$
(< "$label_file")
774 awk -v label
="$label" '{
776 label = sprintf(" (%s)", label)
777 printf("%.2f°C%s\n", $1 / 1000, label)
782 | indent
"$indent_unit"
784 | indent
"${indent_unit}${indent_unit}"
787 #local -r internet_addr=$(internet_addr 0.5)
788 #local -r internet_ptr=$(host -W 1 "$internet_addr" | awk 'NR == 1 {print $NF}' )
790 #echo "${indent_unit}internet"
791 #echo "${indent_unit}${indent_unit}$internet_addr $internet_ptr"
792 echo "${indent_unit}if"
793 (ifconfig
; iwconfig
) 2> /dev
/null \
797 sub(":$", "", device)
800 sub("^ESSID:\"", "", _essid)
801 sub("\"$", "", _essid)
802 essid[device] = _essid
807 /^ / && $1 == "inet" {
812 /^ +Link Quality=[0-9]+\/[0-9]+ +Signal level=/ {
813 split($2, lq_parts_eq, "=")
814 split(lq_parts_eq[2], lq_parts_slash, "/")
815 cur = lq_parts_slash[1]
816 max = lq_parts_slash[2]
817 link[device] = cur / max * 100
822 for (device in address)
823 if (device != "lo") {
826 l = l ? sprintf("%.0f%%", l) : "--"
828 print device, address[device], e, l
833 | indent
"${indent_unit}${indent_unit}"
835 # WARN: ensure: $USER ALL=(ALL) NOPASSWD:/bin/netstat
837 echo "${indent_unit}-->"
839 # TODO Populate pid->cmd dict from `ps -eo pid,comm` and lookup progs there
840 # since netstat -p output comes out truncated.
842 sudo
-n netstat
-tulnp \
843 |
awk -v indent
="${indent_unit}${indent_unit}" '
844 NR > 2 && ((/^tcp/ && proc = $7) || (/^udp/ && proc = $6)) {
847 port = a[split(addr, a, ":")]
848 name = p[split(proc, p, "/")]
850 protocols[protocol] = 1
851 if (!seen[protocol, name, port]++)
852 ports[protocol, name, ++seen[protocol, name]] = port
856 for (protocol in protocols) {
857 printf "%s%s\t", indent, toupper(protocol)
858 for (name in names) {
859 if (n = seen[protocol, name]) {
862 for (i = 1; i <= n; i++) {
863 printf "%s%d", sep, ports[protocol, name, i]
873 echo "${indent_unit}<->"
875 printf '%sTCP\t' "${indent_unit}${indent_unit}"
876 sudo
-n netstat
-tnp \
877 |
awk 'NR > 2 && $6 == "ESTABLISHED" {print $7}' \
878 |
awk '{sub("^[0-9]+/", ""); print}' \
883 # TODO: iptables summary
886 ssh_invalid_by_addr
() {
888 /: Invalid user/ && $5 ~ /^sshd/ {
889 addr=$10 == "port" ? $9 : $10
895 for (addr in by_addr)
896 if ((c = by_addr[addr]) > 1)
897 printf "%d %d %s\n", c, max, addr
901 /var
/log
/auth.log
.1 \
903 | bar_gauge
-v width
="$(stty size | awk '{print $2}')" -v num
=1 -v ch_right
=' ' -v ch_left
=' ' -v ch_blank
=' ' \
907 ssh_invalid_by_day
() {
924 /: Invalid user/ && $5 ~ /^sshd/ {
932 if ((c = by_day[day]) > 1)
933 printf "%d %d %s\n", c, max, day
937 /var
/log
/auth.log
.1 \
939 | bar_gauge
-v width
="$(stty size | awk '{print $2}')" -v num
=1 -v ch_right
=' ' -v ch_left
=' ' -v ch_blank
=' ' \
943 ssh_invalid_by_user
() {
945 /: Invalid user/ && $5 ~ /^sshd/ {
952 for (user in by_user)
953 if ((c = by_user[user]) > 1)
954 printf "%d %d %s\n", c, max, user
958 /var
/log
/auth.log
.1 \
960 | bar_gauge
-v width
="$(stty size | awk '{print $2}')" -v num
=1 -v ch_right
=' ' -v ch_left
=' ' -v ch_blank
=' ' \
968 sub(":$", "", prog[1]) # if there were no [], than : will is left behind
970 }' /var
/log
/syslog
/var
/log
/syslog
.1 \
973 n = split($1, path, "/") # prog may be in path form
981 print count[prog], total, prog
984 | bar_gauge
-v num
=1 -v ch_right
=' ' -v ch_left
=' ' -v ch_blank
=' ' \