carcass-absorb 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #! /bin/bash
  2. usage() {
  3. printf "Usage: %s -[dhv] DIR\n" "$0"
  4. 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"
  5. printf "\n\t-d\tDry run\n\t-h\tPrint this help\n\t-v\tRun verbosely\n"
  6. }
  7. inner_md5_cmd() {
  8. find ./ -type f -print0 | sort -z | xargs -0 md5sum
  9. }
  10. dryrun=0
  11. verbose=0
  12. while getopts dhv opt; do
  13. case $opt in
  14. d) dryrun=1 ;;
  15. v) verbose=1 ;;
  16. h) usage; exit 0 ;;
  17. ?) 2>&1 usage; exit 1 ;;
  18. esac
  19. done
  20. shift $(( OPTIND - 1 ))
  21. objdir=.carcass
  22. [[ -d $objdir ]] || {
  23. if [[ $verbose -eq 1 ]]; then
  24. mkdir -v ./$objdir
  25. else
  26. mkdir ./$objdir
  27. fi
  28. }
  29. [[ -d "$1" ]] || {
  30. 2>&1 printf "%s is not a directory\n" "$1"
  31. exit 1
  32. }
  33. target=$(basename "$1")
  34. if [[ $verbose -eq 1 ]]; then
  35. printf "Targeting '%s'\n" "$target"
  36. pushd "$target"
  37. else
  38. pushd "$target" > /dev/null
  39. fi
  40. md5file=md5sums
  41. [[ -f $md5file ]] && {
  42. 2>&1 printf "%s already exists; refusing to clobber.\n" "$md5file"
  43. exit 2
  44. }
  45. if [[ $verbose -eq 1 ]]; then
  46. printf "Writing md5sums\n"
  47. if [[ $dryrun -eq 0 ]]; then
  48. inner_md5_cmd | grep -v $md5file | tee $md5file
  49. else
  50. inner_md5_cmd
  51. fi
  52. else
  53. if [[ $dryrun -eq 0 ]]; then
  54. inner_md5_cmd | grep -v $md5file > $md5file
  55. fi
  56. fi
  57. popd > /dev/null
  58. if [[ $dryrun -eq 1 ]]; then
  59. printf "Nothing more can be done in dry run. Exiting.\n"
  60. exit 0
  61. fi
  62. if [[ $verbose -eq 1 ]]; then
  63. printf "\nTarring %s\n" "$target"
  64. tar -cvf "$target".tar "$target"/
  65. else
  66. tar -cf "$target".tar "$target"/
  67. fi
  68. md5=$(md5sum "$target".tar | awk '{print $1}')
  69. if [[ $verbose -eq 1 ]]; then
  70. printf "'%s.tar' has md5sum %s\n" "$target" "$md5"
  71. fi
  72. prefix="${md5:0:2}"
  73. suffix="${md5:2}"
  74. mkdir -p ${objdir}/$prefix
  75. if [[ $verbose -eq 1 ]]; then
  76. mv -v "$target".tar ${objdir}/${prefix}/${suffix}.tar
  77. else
  78. mv "$target".tar ${objdir}/${prefix}/${suffix}.tar
  79. fi || exit 4
  80. if [[ $verbose -eq 1 ]]; then
  81. rm -rv "$target"
  82. else
  83. rm -r "$target"
  84. fi