scripts/webpautoconv.bash

125 lines
3.3 KiB
Bash
Raw Normal View History

2024-05-16 21:47:40 +02:00
#!/usr/bin/env bash
# This is an old script of mine that I found again and updated
# to also allow for watching directories recursively.
# This script scans directories for webp files and converts them to
# png files. It can also be run as a daemon that runs whenever a file
# is created in the specified (sub)directories.
launch_daemon() {
if [ -z "$(command -v inotifywait)" ]; then
>&2 echo "inotify-tools are required for daemon mode"
exit 1
fi
if [ -n "$RECURSE" ]; then
scan_dirs=()
for scan_dir in $(find "$SCAN_DIR" -type d); do
scan_dirs+=("$scan_dir")
done
inotifywait -mrq -e create --format %w%f "${scan_dirs[@]}" | while read -r FILE; do
convert_if_webp "$FILE"
done
else
inotifywait -mrq -e create --format %w%f "$SCAN_DIR" | while read -r FILE; do
convert_if_webp "$FILE"
done
fi
}
scan_dir() {
shopt -s globstar nullglob
if [ "$RECURSE" ]; then
for FILE in "$SCAN_DIR"**/**; do
convert_if_webp "$FILE"
done
else
for FILE in "$SCAN_DIR"/*; do
convert_if_webp "$FILE"
done
fi
}
convert_if_webp() {
if [ "$(file -b --mime-type "$FILE")" = "image/webp" ]; then
out_file="${1%.*}"
if [ -f "$out_file.png" ]; then
sha1="$(echo -n "$1" | sha1sum | awk '{print $1}')"
out_file+="-$sha1.png"
else
out_file+=".png"
fi
convert "$1" "$out_file"
echo "Converted $1 to $out_file"
fi
}
verify_option_with_argument() {
if [ -z "$2" ] || [ "${2:0:1}" = "-" ]; then
>&2 echo "Option $1 requires a parameter"
exit 1
fi
}
args() {
while [ -n "$1" ]; do
case "$1" in
"" | "-h" | "--help")
2024-05-16 21:56:40 +02:00
printf "\n\
arguments:\n\
-c/--config [config file] (optional) <The configuration file> {default:~/.config/webpautoconv}\n\
-d/--directory [scan directory] (optional) <The directory to convert files in> {default:~/Downloads}\n\
-w/--watch [none] (optional) <Launch in daemon mode and watch folder> {default:off}\n\
-r/--recursive [non] (optional) <Also scan subdirectories> {default:off}\n"
2024-05-16 21:47:40 +02:00
exit 0
;;
"-c" | "--config")
verify_option_with_argument "$@"
CONF_FILE="$2"
shift 2
;;
"-d" | "--directory")
verify_option_with_argument "$@"
SCAN_DIR="$2"
shift 2
;;
"-w" | "--watch")
DAEMON="true"
shift
;;
"-r" | "--recursive")
RECURSE="true"
shift
;;
esac
done
}
config() {
[ -z "$CONF_FILE" ] && CONF_FILE="$HOME/.config/webpautoconv"
if [ -f "$CONF_FILE" ]; then
# shellcheck source=/dev/null
source "$CONF_FILE"
fi
# Default config options
[ -z "$SCAN_DIR" ] && SCAN_DIR="$HOME/Downloads"
[ -z "$DAEMON" ] && DAEMON="false"
[ -z "$RECURSE" ] && RECURSE="false"
}
main() {
config
args "$@"
scan_dir
if [ "$DAEMON" = "true" ]; then
launch_daemon
fi
}
main "$@"