checksum : rewrite.

This commit is contained in:
Dmitry Voronin 2023-11-23 00:13:51 +03:00
parent a4bb766210
commit 69278cdab8
3 changed files with 62 additions and 6 deletions

View file

@ -657,6 +657,14 @@ Command|Description
By default, umask is `077` which means group and others have no access when files are created. 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. ## Vdl.
Command|Description Command|Description

View file

@ -1,25 +1,68 @@
# Save file checksums.
checksum_create() 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}" echo -e "${color_bred}Checksum already exists.${color_default}"
return 1 return 1
fi fi
find -type f | parallel -- sha1sum {} >> .checksum find -type f | parallel -j $(_core_count) -- sha1sum {} >> "${file}"
sed -i "/\.checksum/d" .checksum sed -i "/${file}/d" ${file}
} }
# Check stored values against actual files.
checksum_check() 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() checksum_update()
{ {
if [[ ! -f .checksum ]]; then local file=".checksum"
if [[ ! -f "${file}" ]]; then
echo -e "${color_bred}Checksum doesn't exists.${color_default}" echo -e "${color_bred}Checksum doesn't exists.${color_default}"
return 1 return 1
fi 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

View file

@ -0,0 +1,5 @@
# Get the number of avaialble cores (threads).
_core_count()
{
cat /proc/cpuinfo | grep ^processor | wc -l
}