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