fant0men

Merge torrent dirs (bash script)

Nov 28th, 2019
177
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/bash
  2. # This script will look for directories in the current dir, called
  3. # "Temporary torrentdir", and merge all found directories in a dir
  4. # called "Torrents". It will also find "md5.db" files, and use a regex
  5. # to change the paths to point to the new "Torrents" directory.
  6.  
  7. cwd=$(readlink -f "$PWD")
  8.  
  9. torrents="${cwd}/Torrents"
  10. md5db_new="${cwd}/md5.db"
  11.  
  12. if [[ ! -d $torrents ]]; then
  13.     mkdir -p "$torrents"
  14. fi
  15.  
  16. if [[ -f $md5db_new ]]; then
  17.     md5db_bak="${md5db_new}.${RANDOM}"
  18.     mv "$md5db_new" "${md5db_bak}"
  19. fi
  20.  
  21. touch "$md5db_new"
  22.  
  23. mapfile -t dirs < <(find . -type d -iname "Temporary torrentdir" -o -iname "Temporary torrent dir")
  24.  
  25. echo "Directories found: ${#dirs[@]}"
  26.  
  27. for (( i = 0; i < ${#dirs[@]}; i++ )); do
  28.  
  29.     line="${dirs[${i}]}"
  30.     echo "Now processing: ${line}"
  31.  
  32.     mv -n "${line}"/* "$torrents"
  33.  
  34.     check=$(ls -1 "$line" 2>&-)
  35.  
  36.     if [[ -z $check ]]; then
  37.         rm -rf "$line"
  38.     fi
  39.  
  40.     md5db_old=$(sed "s|Temporary torrent *dir$|md5.db|" <<<"$line")
  41.  
  42.     if [[ -f $md5db_old ]]; then
  43.  
  44.         mapfile -t md5s_new < <(grep "^Temporary torrent *dir" "$md5db_old" 2>&- | sed "s|^Temporary torrent *dir|Torrents|")
  45.         mapfile -t md5s_old < <(grep -v "^Temporary torrent *dir" "$md5db_old" 2>&-)
  46.  
  47.         if [[ $md5db_new == $md5db_old ]]; then
  48.             truncate --size=0 "$md5db_new"
  49.         fi
  50.  
  51.         for (( j = 0; j < ${#md5s_new[@]}; j++ )); do
  52.  
  53.             md5_new="${md5s_new[${j}]}"
  54.             echo "$md5_new" >> "$md5db_new"
  55.         done
  56.  
  57.         if [[ $md5db_new != $md5db_old ]]; then
  58.  
  59.             truncate --size=0 "$md5db_old"
  60.  
  61.             for (( k = 0; k < ${#md5s_old[@]}; k++ )); do
  62.  
  63.                 md5_old="${md5s_old[${k}]}"
  64.                 echo "$md5_old" >> "$md5db_old"
  65.             done
  66.         fi
  67.     fi
  68.  
  69.     unset -v line md5db_old md5s_new md5s_old md5_new md5_old
  70. done
  71.  
  72. if [[ $md5db_bak ]]; then
  73.     md5db_tmp="${md5db_new}.${RANDOM}"
  74.     cat "$md5db_new" "$md5db_bak" | sed "s|^Temporary torrent *dir|Torrents|" | sort -u > "$md5db_tmp"
  75.  
  76.     rm -f "$md5db_bak"
  77.     mv "$md5db_tmp" "$md5db_new"
  78. fi
RAW Paste Data