Compare commits

...

4 commits

Author SHA1 Message Date
PedoDeveloper
92efe6f85b Added smart volume size algorithm 2024-11-11 12:31:17 +00:00
PedoDeveloper
4a236a56cf Improved input validation 2024-11-11 12:07:49 +00:00
PedoDeveloper
bb075ed369 Added explanation to archive.7z 2024-11-09 07:04:40 +00:00
PedoDeveloper
9515d2c952 Added cleanup function 2024-11-09 06:59:06 +00:00

View file

@ -1,4 +1,6 @@
#!/bin/bash
# This script packs a file or directory into a 7z archive with the given password.
# It can (optionally) split the archives into volumes of a fixed size in megabytes.
archive_dir="$(dirname "$0")/../archives"
@ -6,6 +8,11 @@ input_file="${1}"
archive_pwd="${2}"
size="$3"
cleanup() {
[[ -n "$archive" ]] && rm -f "$archive*"
echo "Cleaned up all $archive files" >&2
}
check_dependencies() {
if ! mkdir -p "$archive_dir"; then
echo "ERROR: Unable to create archive directory"
@ -24,35 +31,49 @@ check_input() {
exit 2
fi
echo "Archiving file/directory '${input_file}'" >&2
if [[ -z "${archive_pwd}" ]]; then
echo "ERROR: No password given"
exit 2
fi
if ! [[ "$size" =~ ^([1-9][0-9]*)?$ ]]; then
echo "Invalid size $size, must be a positive number"
exit 2
fi
echo "Archiving file/directory '${input_file}' with password '${archive_pwd}'" >&2
}
calc_smart_volumes() {
total_size=$(du -s -BM "${input_file}" | grep -oP '^\d+') || return
num_volumes=$(echo "($total_size + $size - 1) / $size" | bc)
size=$(echo "($total_size + $num_volumes - 1) / $num_volumes" | bc)
echo "Calculated smart volume size '$size'" >&2
}
set_volumes() {
volumes=
[[ -z "$size" ]] && return
if [[ "$size" =~ ^[1-9][0-9]*$ ]]; then
volumes="-v${size}m"
elif [[ -n "$size" ]]; then
echo "Invalid size $size, must be a number"
exit 2
fi
calc_smart_volumes
volumes="-v${size}m"
echo "Volumes set to '$volumes'" >&2
}
generate_name() {
archive="$archive_dir/$(base64 /dev/urandom | tr -dc [:alnum:] | head -c 20).7z"
echo "Generated archive name $archive" >&2
echo "Generated archive name '$archive'" >&2
}
create_archive() {
echo "Packing ${input_file} into archive $archive with password ${archive_pwd}"
echo "Packing '${input_file}' into archive '$archive' with password '${archive_pwd}'"
[[ -n "$volumes" ]] && echo "and volumes of size $size MB"
7z a -mhe=on "-p${archive_pwd}" "$volumes" "$archive" "${input_file}" >&2
}
trap cleanup 1 2 3 6
check_dependencies
check_input
set_volumes