glurp : ré-écriture

This commit is contained in:
Ahurac 2024-04-04 12:27:55 +02:00
parent 03e49268f1
commit cb3fc72d2b

126
bin/glurp
View file

@ -1,83 +1,81 @@
#!/bin/bash #!/usr/bin/env sh
# Function to print an error in stderr
declare -A temp_files perror() {
temp_files[command_to_source]=$(mktemp) >&2 printf '\033[1;31mERROR:\033[0m \033[1m%s\033[0m\n' "$*"
clean() {
rm -- "${temp_files[@]}"
} }
usage() { usage() {
cat << EOF name=$(basename "$0")
Usage:
glurp full|area clip|file printf %s "${name}: usage
EOF ${name} f[ull]|a[rea] c[lip]|f[ile]
} ${name} -h
"
error() {
>&2 printf '\033[0m\033[1;31mERROR:\033[0m \033[1m%s\033[0m\n' "$*"
} }
# Function to throw an error usage
error_usage() { error_usage() {
error "Invalid usage" perror "invalid usage"
>&2 usage >&2 usage
}
error_usage_clean() { exit 1
error_usage
clean
} }
screenshot_path() { screenshot_path() {
local path if [ -d "$XDG_RUNTIME_DIR" ]; then
if [ -n "$1" ]; then base=${XDG_RUNTIME_DIR}/screenshots
path="$1" else
else base=/tmp/${USER}-screenshots
path=. fi
fi
mkdir -p "$path" # I literally know, shellcheck
printf '%sscreenshot-%s.png' "${path}/" "$(date +%Y_%m_%d_%H_%M_%S_%N)" # shellcheck disable=2174
mkdir -p -m 700 -- "$base"
printf %s "${base}/screenshot-$(date +%Y%m%d_%H%M%S%N).png"
} }
trap error_usage_clean EXIT while getopts :h opt; do
set -e case "$opt" in
h)
usage
exit 0
;;
?)
error_usage
;;
esac
done
slurp=() # Initial variables
grim_args=() slurp=
wl_copy=() grim="grim -t png"
clipboard=
# f* = full, a* = area
case "$1" in case "$1" in
full) f*) : ;;
: a*)
;; slurp="slurp |"
area) grim="${grim} -g -"
slurp+=(slurp \|) ;;
grim_args+=(-g -) *) error_usage ;;
;;
*)
false
;;
esac esac
shift
case "$1" in # c* = clip, f* = file
clip) case "$2" in
wl_copy+=(\| wl-copy -t image/png) c*)
grim_args+=(-) grim="${grim} -o -"
;; clipboard="| wl-copy -t image/png"
file) ;;
grim_args+=("$(screenshot_path "${XDG_RUNTIME_DIR:-/tmp/$(whoami)}/screenshots")") f*)
;; grim="${grim} -o '$(screenshot_path)'"
*) ;;
false *) error_usage ;;
;;
esac esac
shift
cat > "${temp_files[command_to_source]}" << EOF set -- sh -c "${slurp} ${grim} ${clipboard}"
${slurp[@]} grim ${grim_args[@]} ${@} ${wl_copy[@]} set -x
EOF #: "$@"
#exit
trap clean EXIT exec "$@"
sh -s < "${temp_files[command_to_source]}"