WizdomWeb/scripts/convert-to-webp.sh

112 lines
2.9 KiB
Bash
Executable File

#!/bin/bash
#
# File: convert-to-webp.sh
# Version: 0.9
# Path: /scripts/image/
# Purpose: Convert PNG/JPEG to WebP with hashing, metadata checks, logging, and smart skip/delete/report options.
# Project: Wizdom Networks Website Optimization
#
# Usage:
# ./convert-to-webp.sh [options] <input_folder>
#
# Options:
# --noskip Process all files regardless of hash or metadata match
# --DELETE Delete original file after successful conversion
# --report Show hash, size, mod date comparison per file
# --log <path> Write output to log file at specified path
# --nolog Disable logging
# --help Show this help message and exit
set -e
# === Defaults ===
SKIP=true
DELETE=false
REPORT=false
LOGGING=true
LOG_FILE="./conversion.log"
# === Helper: Print Help ===
print_help() {
grep '^# ' "$0" | sed 's/^# //'
exit 0
}
# === Helper: Log ===
log() {
if [ "$LOGGING" = true ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO]: $1" | tee -a "$LOG_FILE"
fi
}
# === Helper: Get File Metadata Hash ===
get_file_info() {
local file="$1"
sha256sum "$file" | cut -d' ' -f1
}
# === Parse Arguments ===
while [[ "$1" =~ ^-- ]]; do
case "$1" in
--noskip) SKIP=false ;;
--DELETE) DELETE=true ;;
--report) REPORT=true ;;
--nolog) LOGGING=false ;;
--log)
shift
LOG_FILE="$1"
;;
--help) print_help ;;
*) echo "Unknown option: $1" && print_help ;;
esac
shift
done
INPUT_DIR="$1"
[ -z "$INPUT_DIR" ] && echo "Error: No input folder provided." && print_help
[ ! -d "$INPUT_DIR" ] && echo "Error: '$INPUT_DIR' is not a valid directory." && exit 1
log "Starting conversion in folder: $INPUT_DIR"
find "$INPUT_DIR" -type f \( -iname "*.png" -o -iname "*.jpg" -o -iname "*.jpeg" \) | while read -r src; do
dest="${src%.*}.webp"
if [ "$SKIP" = true ] && [ -f "$dest" ]; then
src_hash=$(get_file_info "$src")
dest_hash=$(get_file_info "$dest")
src_size=$(stat -c %s "$src")
dest_size=$(stat -c %s "$dest")
src_time=$(stat -c %Y "$src")
dest_time=$(stat -c %Y "$dest")
if [ "$src_hash" == "$dest_hash" ] || ([ "$src_size" == "$dest_size" ] && [ "$src_time" -eq "$dest_time" ]); then
log "SKIPPED: $src (already converted)"
continue
fi
fi
log "Converting: $src$dest"
if convert "$src" -strip -quality 85 "$dest"; then
log "SUCCESS: $dest created."
if [ "$DELETE" = true ]; then
rm "$src"
log "DELETED: $src"
fi
else
log "ERROR: Failed to convert $src"
fi
if [ "$REPORT" = true ]; then
echo "REPORT for: $src"
echo " Source Hash: $(get_file_info "$src")"
echo " Dest Hash: $(get_file_info "$dest")"
echo " Source Size: $(stat -c %s "$src")"
echo " Dest Size: $(stat -c %s "$dest")"
echo " Source mtime: $(stat -c %y "$src")"
echo " Dest mtime: $(stat -c %y "$dest")"
echo ""
fi
done
log "Conversion complete."