#!/usr/bin/env bash # exit if required variables are not set set -o nounset # subshells and functions inherit ERR traps set -E # pass debug value to child scripts DEBUG="${DEBUG:-0}" export DEBUG # number of threads to use if [[ ${DEBUG} -eq 1 ]]; then echo "Running single thread for debugging" parallel_thread_count=1 else parallel_thread_count=8 fi # exit if lock file exists, otherwise create it lock_file="/run/user/$(id -ru)/optimize-pngs.lock" if [ -f "${lock_file}" ]; then echo "Process already running at pid $(cat "${lock_file}")." exit 0 fi echo "$$" > "${lock_file}" # remove lock file on exit function cleanup { if ! { rm "${lock_file}"; }; then echo "Cleanup failed. You may need to manually remove ${lock_file}." fi } trap cleanup EXIT # create and display temporary directory base_dir="$(mktemp -d)" if [[ ${DEBUG} -eq 1 ]]; then echo "Temporary files will be written to ${base_dir}." fi # command list location commands="${base_dir}/commands.txt" if [[ ${DEBUG} -eq 1 ]]; then echo "Storing commands for $(pwd) in ${commands}" fi # generate list of commands to run while read -r path; do echo "cd \"${path}\"; optimize-pngs.sh ${base_dir}; cd .." >> "${commands}" done <<< "$(find "$(pwd -P)" -maxdepth 1 -type d)" # run list of commands in parallel parallel --no-notice --jobs "${parallel_thread_count}" < "${commands}" # prompt to remove temporary directory SHELLNOCASEMATCH=$(shopt -p nocasematch; true) shopt -s nocasematch read -r -p 'Delete temporary directory? [y/N]: ' remove_temp_dir if [[ "${remove_temp_dir}" == "y" ]]; then rm -rf "${base_dir}" fi $SHELLNOCASEMATCH