#!/bin/bash
# === Настройки ===
TARGET_DIR="${1:-.}"
DRY_RUN=false
FORCE_ALL=true
REPLACE_SPACES=false
# === Защищённые расширения (файлы с такими расширениями пропускаются) ===
# OpenPGP/GnuPG: sig, asc, pgp, gpg
# S/MIME PKCS#7: p7s, p7c, p7b, p7d, p7r, spc
# КриптоПро/ГОСТ: sgn, sign
PROTECTED_EXT=("sig" "asc" "pgp" "gpg" "p7s" "p7c" "p7b" "p7d" "p7r" "spc" "sgn" "sign")
# === Таблица MIME -> расширение ===
declare -A MIME_TO_EXT=(
["application/pdf"]="pdf"
["application/vnd.openxmlformats-officedocument.wordprocessingml.document"]="docx"
["application/msword"]="doc"
["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]="xlsx"
["application/vnd.ms-excel"]="xls"
["application/vnd.openxmlformats-officedocument.presentationml.presentation"]="pptx"
["application/vnd.ms-powerpoint"]="ppt"
["application/zip"]="zip"
["application/x-tar"]="tar"
["application/gzip"]="gz"
["application/x-bzip2"]="bz2"
["application/x-xz"]="xz"
["image/jpeg"]="jpg"
["image/png"]="png"
["image/gif"]="gif"
["image/svg+xml"]="svg"
["text/plain"]="txt"
["text/html"]="html"
["text/x-shellscript"]="sh"
["inode/x-empty"]=""
)
rename_file() {
local oldpath="$1"
local newpath="$2"
if [[ "$oldpath" == "$newpath" ]]; then
return
fi
if [[ "$DRY_RUN" == true ]]; then
echo "[DRY RUN] mv '$oldpath' '$newpath'"
else
mv -n "$oldpath" "$newpath" && echo "✓ $oldpath -> $newpath"
fi
}
export DRY_RUN REPLACE_SPACES PROTECTED_EXT
export -f rename_file
export MIME_TO_EXT
find "$TARGET_DIR" -type f -print0 | while IFS= read -r -d '' filepath; do
filename=$(basename -- "$filepath")
dirname=$(dirname -- "$filepath")
# Определяем расширение (часть после последней точки)
if [[ "$filename" == *.* ]]; then
ext="${filename##*.}"
else
ext=""
fi
# Пропускаем файлы с защищёнными расширениями
if [[ -n "$ext" ]] && [[ " ${PROTECTED_EXT[@]} " =~ " ${ext} " ]]; then
continue
fi
# Базовое имя (до первой точки или всё, если точки нет)
if [[ "$filename" == *.* ]]; then
base="${filename%%.*}"
else
base="$filename"
fi
if [[ "$REPLACE_SPACES" == true ]]; then
base="${base// /_}"
fi
mime=$(file --mime-type -b "$filepath" 2>/dev/null)
if [[ -z "$mime" ]]; then
echo "⚠ Не удалось определить MIME-тип: $filepath" >&2
continue
fi
new_ext="${MIME_TO_EXT[$mime]}"
if [[ -z "$new_ext" ]]; then
continue
fi
new_filename="${base}.${new_ext}"
new_filepath="${dirname}/${new_filename}"
rename_file "$filepath" "$new_filepath"
done
echo "Готово."