-
Notifications
You must be signed in to change notification settings - Fork 2
/
.functions
executable file
·495 lines (436 loc) · 16.4 KB
/
.functions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
#!/bin/bash
# -----------------------------------------------------------------------------
# opening helpers
mp() { mpv --window-scale=0.1 --loop "$(fzf)" ;} # > /dev/null 2>&1
mp2() { mpv --speed=2 "$(fzf)" ;} # > /dev/null 2>&1
h() { $EDITOR . ;}
# -----------------------------------------------------------------------------
# zellij + terminal mux helpers
# shellcheck disable=SC2068
rc() { zellij run -- $@ ;}
# shellcheck disable=SC2068
ra() { zellij run -- zsh -ic $@ ;}
# zellij tab from layout
zl() {
local -r layout="$(cd ~/.config/zellij/layouts && fd . -x echo '{.}' | fzf)"
zellij action new-tab --layout "${layout}"
}
# terminal mux helpers to rename the tab we do something
zz() {
if [ -n "${ZELLIJ_SESSION_NAME}" ]; then
zellij action rename-tab "${PWD##*/}"
fi
}
# ensure directory traversal updates tab names (if terminal mux exists)
chpwd_functions+=zz
zz # initialize name for new tabs/panes
# -----------------------------------------------------------------------------
# Key management via keychain
key() {
local keys=()
for k in "$@"; do
case $k in
tl) keys+=("E58AB0A39760D799 ") ;;
pass) keys+=("B71E94106D1B408B") ;; # enc subkey
sign) keys+=("5D4B685DE5BEAE01") ;; # signing subkey
*) keys+=("${k}_id") ;; # assume ssh key
esac
done
# shellcheck disable=SC2068
keychain --nogui --timeout $((16*60)) --quiet --host agent --agents ssh,gpg ${keys[@]}
source ~/.keychain/agent-sh
source ~/.keychain/agent-sh-gpg
}
keys() {
# join static list of gpg keys with dynamic list of ssh keys
local -r available="$( ( (fd --max-depth 1 -u --type f -g '*_id' ~/.ssh | cut -d'/' -f5 | sed 's/_id//g'); echo -e "tl\npass\nsign") | fzf )"
# shellcheck disable=SC2086
key $available
}
# -----------------------------------------------------------------------------
# fzf interfaces
passz() {
# TODO: force a gpg prompt here
# TODO: better sanitization strategy for deets (not safe to show atm)
fd --base-directory ~/.password-store .gpg --type=file | choose 0 -f '.gpg' \
| fzf --no-sort --reverse --height 100% --tiebreak=index \
--header="Enter:deets, F3:clip, ESC:quit, q:quit-deets" \
--bind="ctrl-m:execute:(pass {1} | tail -n +2 | less -R)" \
--bind="F3:execute:(pass {1} -c)"
}
# chrome history
ch() {
local cols sep open
cols=$(( COLUMNS / 3 ))
sep='{::}'
open='xdg-open'
if [[ "${OSTYPE}" =~ "darwin" ]]; then
open="open"
cp -f ~/Library/Application\ Support/Google/Chrome/Default/History /tmp/h
else
cp -f ~/.config/google-chrome/Default/History /tmp/h
fi
sqlite3 -separator $sep /tmp/h \
"select substr(title, 1, $cols), url
from urls order by last_visit_time desc" |
awk -F $sep '{printf "%-'$cols's \x1b[36m%s\x1b[m\n", $1, $2}' |
fzf --ansi --multi | sed 's#.*\(https*://\)#\1#' | \
xargs "${open}" > /dev/null
}
# systemd unit and log viewer
# start with sysu or sysf and toggle with ctrl-u
_sysf() {
local -r userarg="$1"
local -r sudopref="$2"
local -r _sysf_toggle="$3"
local -r _sysf_list="systemctl list-units --no-pager --no-legend $1"
local -r _sysf_list_cmd=("systemctl" "list-units" "--no-pager" "--no-legend" "$1")
# shellcheck disable=SC2086,SC2068,SC2091
${_sysf_list_cmd[@]} | choose 0 | grep -E ".service$" \
| fzf --layout=reverse --header-lines=0 --info=inline --height=100% \
--header="ESC:exit, F4:show, F5/F6: start/stop, F7/F8: enable/disable F9:restart, F10: dr" \
--bind="ctrl-r:reload(${_sysf_list} | choose 0 | grep -E .service$)" \
--bind="ctrl-u:become(source ~/.functions && ${_sysf_toggle})" \
--bind="f4:execute:(SYSTEMD_COLORS=1 ${sudopref} systemctl show ${userarg} {1})" \
--bind="f5:execute-silent:(${sudopref} systemctl start ${userarg} {1})" \
--bind="f6:execute-silent:(${sudopref} systemctl stop ${userarg} {1})" \
--bind="f7:execute-silent:(${sudopref} systemctl enable ${userarg} {1})" \
--bind="f8:execute-silent:(${sudopref} systemctl disable ${userarg} {1})" \
--bind="f9:execute-silent:(${sudopref} systemctl restart ${userarg} {1})" \
--bind="f10:execute-silent:(${sudopref} systemctl daemon-reload ${userarg})" \
--preview="SYSTEMD_COLORS=1 ${sudopref} systemctl status ${userarg} {1}; SYSTEMD_COLORS=1 systemctl cat ${userarg} {1}" \
--preview-window="right:55%" \
--bind="enter:execute(journalctl -u {} ${userarg} | less +G -R)"
}
sysz() { _sysf "" "sudo" "sysu" ;}
sysu() { _sysf "--user" "" "sysz" ;}
# mount a usb partition with udisks2 - alternative; just use udiskie
mountz() {
# NB: probably assumes a lot, but works for me..
# TODO: could simplify with lsblk -J | jq
local -r part="$(lsblk -r | grep " part" | grep -v nvme | choose 0 | fzf)"
udisksctl mount -b "${part}" # needs to have the partition number e.g. /dev/sda1
}
# pacman experiment
pacq() {
pacman -Qq | fzf --preview 'pacman -Qil {}' --height=100% --layout=reverse --bind 'enter:execute(pacman -Qil {} | less)'
}
# -----------------------------------------------------------------------------
# package manager abstraction - mostly for my own memory
if [[ "${OSTYPE}" =~ "darwin" ]]; then
qlist() { brew list "$1" ;}
pakl() { brew leaves ;}
# no pakf (cannot search registry for files)
# no pakl (look at what symlinks point to instead)
paki() { brew install "$1" ;}
pakr() { brew rm "$1" ;}
elif grep -q "Arch Linux" /etc/os-release; then
# list available packages:
paks() { pacman -Ss "$1" ;}
# list locally installed packages:
pakl() { pacman -Qs "$1" ;}
# what package owns local file:
pakf() { pacman -Qo "$1" ;}
# what package owns a file you don't have:
pakq() { pacman -Fs "$1"; } # may need a pacman -Fy first
# list files belonging to a package:
qlist() { pacman -Ql "$1" ;}
# install a package:
paki() { sudo pacman -S "$1" ;}
# remove a package and its dependencies recursively:
pakr() { sudo pacman -Rs "$1" ;}
# list available updates to installed packages:
#canonical checkupdates
elif grep -qE "Ubuntu|Mint" /etc/os-release; then
paks() { apt-cache search "$1"; }
# the easier ones for this all perform network queries..
pakl() { dpkg --get-selections | grep -v deinstall | awk '{ printf("%s\n", $1) }' | grep "$1" ;}
pakf() { dpkg -S "$1" ;}
pakq() { apt-file search "$1" ;} # needs apt-file installed + `apt-file update` called
qlist() { dpkg-query -L "$1" ;}
paki() { sudo apt-get install "$1" ;}
pakr() { sudo apt-get remove "$1" ;}
elif lsb_release -ds | grep -qEi "Gentoo"; then
paks() { eix -c "$1" ;}
pakf() { equery belongs "$1" ;}
# canonical qlist
paki() { sudo emerge "$1" ;}
pakr() { sudo emerge -cav "$1" ;}
checkupdates() { eix -uc "$1" ;}
elif command -v yum &> /dev/null; then
paks() { yum search "$1" ;}
pakf() { yum whatprovides "$1" ;}
qlist() { repoquery --list "$1" ;} # from yum-utils
paki() { sudo yum install "$1" ;}
pakr() { sudo yum remove "$1" ;}
elif grep -qE "Alpine Linux" /etc/os-release; then
paks() { apk info -vv | grep "$1" ;}
pakl() { apk search "$1" ;} # needs an apk update first
pakf() { apk info --who-owns "$1" ;}
#pakq() {} # needs apk-file installed - go get github.com/jessfraz/apk-file outside
qlist() { apk info -L "$1" ;}
paki() { apk add --no-cache "$1" ;}
pakr() { apk del "$1" ;}
fi
# -----------------------------------------------------------------------------
# misc
# if needed
#if [[ ! "${OSTYPE}" =~ "darwin" ]]; then
# # main machines are amd64, rely on arch bin on mac
# arch() {
# echo "amd64"
# }
#fi
# Create a new directory and enter it
mkd() { mkdir -p "$@" && cd "$@" || return 1 ;}
docker-clean() {
docker ps -aq | xargs -r docker rm -f
docker images -q -f="dangling=true" | xargs -r docker rmi -f
docker buildx prune
# check with docker buildx du --verbose
}
serve() {
python -m http.server 8000
}
# upload a single file in PWD to transfer.sh
transfersh() {
curl --upload-file "$1" "https://transfer.sh/$1" | wl-copy
}
# Not sure this works anymore - even on linux; renderer ps are not 1-1 with tabs :/
kill-tabs() { pkill -u "$USER" -f "chrome.*renderer" ;}
# horizontal ruler
hr() {
echo "$(tput setaf 33)$(printf '%.s─' $(seq 1 "$(tput cols)"))"
}
wifihotspot() {
sudo create_ap wlp2s0 enp0s20f0u1 "Bathroom Cam 2" "$(pass network/ea-laptop)"
}
# -----------------------------------------------------------------------------
# gaming related linux hacks
# TODO: try https://github.com/ec-/Quake3e/blob/master/BUILD.md and SDL_VIDEODRIVER=wayland
# https://aur.archlinux.org/packages/quake3-cpma works with all quake3 deps
# the below setup was for X with DMA sound buffers - was super buggy
q3() {
set -x
# Get most of quake3 from https://aur.archlinux.org/quake3-cpma.git (not pak0.pk3)
export __GL_SYNC_TO_VBLANK=0
# Need alsa-oss package and need to enable oss kernel modules
sudo modprobe snd_seq_oss
sudo modprobe snd_pcm_oss
sudo modprobe snd_mixer_oss
# Find correct card by looking in /proc/asound/cards
# Mine jumps around, but its identifier is STX (Asus Xonar STX) - map to number:
local -r cardid=$(grep STX /proc/asound/cards | awk '{print $1}')
# Give DMA Access
# NB: If you screw with this badly and it doesn't work, boot.
echo "quake3.x86 0 0 direct" | sudo tee "/proc/asound/card${cardid}/pcm0p/oss"
echo "quake3.x86 0 0 disable" | sudo tee "/proc/asound/card${cardid}/pcm0c/oss"
# Have "seta snddevice /dev/dsp${cardid}" in your q3config.cfg
# Or use this start command twice (for some reason it doesn't take first start)
aoss quake3-cpma +"seta snddevice /dev/dsp${cardid}"
# Do not open chrome and start playing music in the background
# First sound you hear after boot should be quake
}
# -----------------------------------------------------------------------------
# misc node/py
node-deps() {
npm ls | grep -oE "[[:alnum:]\@\.]*" | sort -u
}
npm-patch() {
npm version patch && git push && git push --tags && npm publish
}
npm-minor() {
npm version minor && git push && git push --tags && npm publish
}
npm-major() {
npm version major && git push && git push --tags && npm publish
}
venv() {
if [ -d venv ]; then
source venv/bin/activate
elif [ -d .venv ]; then
source .venv/bin/activate
else
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
fi
}
# -----------------------------------------------------------------------------
# extraction shortcuts
# insert xkcd tar joke here
extract () {
if [ -f "$1" ] ; then
case "$1" in
*.tar.bz2) tar xvjf "$1" ;;
*.tar.gz) tar xvzf "$1" ;;
*.tar.xz) tar xvJf "$1" ;;
*.bz2) bunzip2 "$1" ;;
*.rar) unrar x "$1" ;;
*.gz) gunzip "$1" ;;
*.tar) tar xvf "$1" ;;
*.tbz2) tar xvjf "$1" ;;
*.tgz) tar xvzf "$1" ;;
*.zip) unzip "$1" ;;
*.Z) uncompress "$1" ;;
*.7z) 7z x "$1" ;;
*) echo "unknown extension for '$1'" ;;
esac
else
echo "$1 is not a valid file!"
fi
}
# ball: output [inputs]
ball () { tar czf "$1.tar" "${@:2}" ;}
# 7zsplit output [inputs]
7zsplit() { 7z a "$1.7z" -mx0 -V500M "${@:2}" ;}
# -----------------------------------------------------------------------------
# storage manipulation (mostly linux only)
openimage() {
local types='*.jpg *.JPG *.png *.PNG *.gif *.GIF *.jpeg *.JPEG'
cd "$(dirname "$1")" || true
local -r file=$(basename "$1")
# shellcheck disable=SC2086
feh -q $types --auto-zoom \
--sort filename --borderless \
--scale-down --draw-filename \
--image-bg black \
--start-at "$file"
}
dslrdump() {
cd /media/gauss/IMG/ || return
mkd "$(date +%F)"
gphoto2 --get-all-files
#gphoto2 --delete-all-files doesn't work :( - pantheon-photos works though
}
# veracrypt shortcuts
vc1() {
sudo echo "got sudo" # cache sudo first
# For some reason the below cmd does not work without non-interactive in text mode
veracrypt -t --mount /dev/sda1 --slot=1 --verbose -p "$(pass drives/turing)" --non-interactive
export HISTFILE=/dev/null
cd /media/veracrypt1 || false
}
vc2() {
sudo echo "got sudo" # cache sudo first
# For some reason the below cmd does not work without non-interactive in text mode
veracrypt -t --mount /dev/sda1 --slot=2 --verbose -p "$(pass drives/hilbert)" --non-interactive
export HISTFILE=/dev/null
cd /media/veracrypt2 || false
}
vcc() {
cd || true
veracrypt --text --dismount /dev/sdc1 --dismount /dev/sde1
exit
}
# -----------------------------------------------------------------------------
# Broxy + brotorr integrations (massively out of date)
# Download dir for `dl` + brotorr
export DOWNLOAD_DIR=~/Downloads
if [[ $HOSTNAME = kjttks ]]; then
export DOWNLOAD_DIR=/media/gauss/DL
elif [[ $HOSTNAME = broxy ]]; then
export DOWNLOAD_DIR=/media/dumptruck/DL
fi
# Download dir for `dl` + brotorr
dl() { cd "$DOWNLOAD_DIR" || return 1 ;}
movies-diff () {
diff -u <(ls /media/clux/TOOL/MP4/Movies/) <(ls /media/clux/Zorn/NewMP4/BluRay/)
}
# xdg-mime handler
broxy-download () {
# shellcheck disable=SC2029
ssh broxy "source ~/.path; source ~/.exports; ./brotorr/torrent \"$1\""
}
# Find flags for helpers
broxy-findflags() {
echo -e "-not -name '.*' -not -regex '.*Trash.*' -not -name tmp -printf '%p\n'"
}
broxy-dirflags() { echo -e "-mindepth $1 -maxdepth $1 -type d" ;}
# Everything in DL - usually fetch from here
broxy-check() {
# shellcheck disable=SC2029
ssh broxy "cd dumptruck/DL && find . $(broxy-dirflags 1) $(broxy-findflags)"
}
# Everything
broxy-all() {
# shellcheck disable=SC2029
ssh broxy "cd dumptruck && find . $(broxy-dirflags 2) $(broxy-findflags)"
}
# Everything from last month
broxy-latest() {
# shellcheck disable=SC2029
ssh broxy "cd dumptruck && find . $(broxy-dirflags 2) -mtime -31 $(broxy-findflags)"
}
# Grab from broxy with a pattern with confirmation
broxy-grab() {
local -r rs=$(broxy-all | grep "$1")
echo "Will download:"
echo "$rs"
read -rp "Enter to continue.."
echo "Starting download"
echo "$rs" | while read -r line; do
fldr=$(echo "$line" | cut -d '/' -f2-)
echo "Downloading $fldr"
rsync -cahzP -e ssh "broxy:/home/bro/dumptruck/$fldr" .
done
notify-send "completed download of $1"
}
# -----------------------------------------------------------------------------
# jira shortcuts
# via https://crates.io/crates/jira-terminal
jira-set() {
jira-terminal list -p ENOPS -S "In Progress" -a "Eirik Albrigtsen" -J \
| jq '.[] | .key + " :: " + .summary' -r \
| fzf --header="Enter:set, F3:open, F4:risk" \
--bind="f4:execute(jira-terminal update -f risk -v Low {1})" \
--bind="f3:execute:(open 'https://truelayer.atlassian.net/browse/{1}')" \
--preview='jira-terminal detail -f all {1}' \
--preview-window=down:80% --height=100% \
| choose 0 -f " :: " > ~/.jira_story
}
jira-risk() {
if [ -f ~/.jira_story ]; then
jira-terminal update -f risk -v "Low" "$(cat ~/.jira_story)"
else
echo "Set story first"
return 1
fi
}
jira-clean() {
rm -f ~/.jira_story
}
# -----------------------------------------------------------------------------
# system statistics/usage - linux only - for my own memory
# better ways of displaying this via fastfetch configs herein
mem() {
free -t | grep Mem | awk '{ printf("%3.1f%%\n", $3*100/$2)}'
}
disk() {
# Total usage of currently mounted logical drives
df -l --total -x tmpfs \
| grep total \
| awk '{printf("%3.1f%%\n", $3*100/$2)}'
}
cpu() { awk '{printf("%3.1f%%\n", $1*100/'"$(nproc)"') }' < /proc/loadavg ;}
# average cpu frequency based on current mean info across cores /proc/cpuinfo divided by max
cpufreq() {
local -r maxkhz="$(cat /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq)"
local -r current_mhz="$(grep 'cpu MHz' /proc/cpuinfo | awk '{print $4}' | datamash mean 1)"
echo "scale=2; 100* $current_mhz * 1000 / $maxkhz" | bc -l | xargs printf "%s%%\n"
}
iface() {
# first interface with state UP
ip link show | grep "state UP" | awk '{print $2}' | cut -d':' -f1 | head -n 1
}
network() {
# transferred numbers are in first column, print everything with space separation
local -r netdata=$(ip -s link show "$(iface)" | awk -v ORS=" " '{ print $1 }')
# convert relevant numbers to gigabytes
local -r RX=$(echo "$netdata" | cut -d" " -f4 | awk '{printf("%3.1fGB\n", $1/1073741824)}')
local -r TX=$(echo "$netdata" | cut -d" " -f6 | awk '{printf("%3.1fGB\n", $1/1073741824)}')
echo -e "Sent: ${TX}\nRecv: ${RX}"
}
localip() {
ip addr show "$(iface)" | grep inet | awk '{ print $2 }'
}