diff --git a/modules/archive.sh b/modules/archive.sh index 593b2ee..62ba886 100755 --- a/modules/archive.sh +++ b/modules/archive.sh @@ -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