12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- #! /bin/bash
- usage() {
- printf "Usage: %s -[dhv] DIR\n" "$0"
- printf "\nEnter DIR, grab the md5sums of all the files in there, then tar the directory up and move it to an object named after its own md5sum.\n"
- printf "\n\t-d\tDry run\n\t-h\tPrint this help\n\t-v\tRun verbosely\n"
- }
- inner_md5_cmd() {
- find ./ -type f -print0 | sort -z | xargs -0 md5sum
- }
- dryrun=0
- verbose=0
- while getopts dhv opt; do
- case $opt in
- d) dryrun=1 ;;
- v) verbose=1 ;;
- h) usage; exit 0 ;;
- ?) 2>&1 usage; exit 1 ;;
- esac
- done
- shift $(( OPTIND - 1 ))
- objdir=.carcass
- [[ -d $objdir ]] || {
- if [[ $verbose -eq 1 ]]; then
- mkdir -v ./$objdir
- else
- mkdir ./$objdir
- fi
- }
- [[ -d "$1" ]] || {
- 2>&1 printf "%s is not a directory\n" "$1"
- exit 1
- }
- target=$(basename "$1")
- if [[ $verbose -eq 1 ]]; then
- printf "Targeting '%s'\n" "$target"
- pushd "$target"
- else
- pushd "$target" > /dev/null
- fi
- md5file=md5sums
- [[ -f $md5file ]] && {
- 2>&1 printf "%s already exists; refusing to clobber.\n" "$md5file"
- exit 2
- }
- if [[ $verbose -eq 1 ]]; then
- printf "Writing md5sums\n"
- if [[ $dryrun -eq 0 ]]; then
- inner_md5_cmd | grep -v $md5file | tee $md5file
- else
- inner_md5_cmd
- fi
- else
- if [[ $dryrun -eq 0 ]]; then
- inner_md5_cmd | grep -v $md5file > $md5file
- fi
- fi
- popd > /dev/null
- if [[ $dryrun -eq 1 ]]; then
- printf "Nothing more can be done in dry run. Exiting.\n"
- exit 0
- fi
- if [[ $verbose -eq 1 ]]; then
- printf "\nTarring %s\n" "$target"
- tar -cvf "$target".tar "$target"/
- else
- tar -cf "$target".tar "$target"/
- fi
- md5=$(md5sum "$target".tar | awk '{print $1}')
- if [[ $verbose -eq 1 ]]; then
- printf "'%s.tar' has md5sum %s\n" "$target" "$md5"
- fi
- prefix="${md5:0:2}"
- suffix="${md5:2}"
- mkdir -p ${objdir}/$prefix
- if [[ $verbose -eq 1 ]]; then
- mv -v "$target".tar ${objdir}/${prefix}/${suffix}.tar
- else
- mv "$target".tar ${objdir}/${prefix}/${suffix}.tar
- fi || exit 4
- if [[ $verbose -eq 1 ]]; then
- rm -rv "$target"
- else
- rm -r "$target"
- fi
|