From 69278cdab8fb21b789a1bd874d41ec794eae3782 Mon Sep 17 00:00:00 2001 From: home Date: Thu, 23 Nov 2023 00:13:51 +0300 Subject: [PATCH] checksum : rewrite. --- .README.md | 8 +++++ .config/bash/module/checksum.sh | 55 +++++++++++++++++++++++++++++---- .config/bash/module/util.sh | 5 +++ 3 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 .config/bash/module/util.sh diff --git a/.README.md b/.README.md index 8707c42..dd8473a 100644 --- a/.README.md +++ b/.README.md @@ -657,6 +657,14 @@ Command|Description By default, umask is `077` which means group and others have no access when files are created. +## Util. + +Short util functions. + +Command|Description +---|--- +`_core_count`|Get number of available CPU threads. + ## Vdl. Command|Description diff --git a/.config/bash/module/checksum.sh b/.config/bash/module/checksum.sh index 1c7406d..858352f 100644 --- a/.config/bash/module/checksum.sh +++ b/.config/bash/module/checksum.sh @@ -1,25 +1,68 @@ +# Save file checksums. checksum_create() { - if [[ -f .checksum ]]; then + local file=".checksum" + + # Error if checksum already exists. + if [[ -f "${file}" ]]; then echo -e "${color_bred}Checksum already exists.${color_default}" return 1 fi - find -type f | parallel -- sha1sum {} >> .checksum - sed -i "/\.checksum/d" .checksum + find -type f | parallel -j $(_core_count) -- sha1sum {} >> "${file}" + sed -i "/${file}/d" ${file} } +# Check stored values against actual files. checksum_check() { - sha1sum --quiet -c .checksum + local file=".checksum" + local failed=0 + + cat "${file}" | parallel -j $(_core_count) -- _checksum_check {} || ((failed++)) + + if [[ ${failed} = 0 ]]; then + echo -e "${color_green}All successful.${color_default}" + return 0 + else + # echo -e "${color_bred}Items failed to validate: ${failed}.${color_default}" + return 1 + fi } +# Check old values and create new one if all was fine. checksum_update() { - if [[ ! -f .checksum ]]; then + local file=".checksum" + + if [[ ! -f "${file}" ]]; then echo -e "${color_bred}Checksum doesn't exists.${color_default}" return 1 fi - checksum_check && rm .checksum && checksum_create + checksum_check && rm "${file}" && checksum_create } + +_checksum_check() +{ + local file="${1##*\ \ }" + local stored="${1%%\ \ *}" + local failed=0 + + # Skip if no file. + [[ -f "${file}" ]] || return 0 + + # Check file hash. + local actual=$(sha1sum "${file}") + actual="${actual%%\ \ *}" + + # Compare values. + if [[ "${stored}" != "${actual}" ]]; then + echo -e "${color_bred}${file}: Failed.${color_default}" + return 1 + fi + + return 0 +} + +export -f _checksum_check diff --git a/.config/bash/module/util.sh b/.config/bash/module/util.sh new file mode 100644 index 0000000..d28d724 --- /dev/null +++ b/.config/bash/module/util.sh @@ -0,0 +1,5 @@ +# Get the number of avaialble cores (threads). +_core_count() +{ + cat /proc/cpuinfo | grep ^processor | wc -l +}