#!/bin/bash
#@version 0.2
#@date 2019-01-22

cd /srv/services/log_movie_changes/md5

#sort & del dublicates
cat data_shares_Filme | sort -k 2 | uniq > data_shares_Filme_tmp
cat data_shares_Filme_tmp > data_shares_Filme

cat data_shares_Filme_tmp | while read line; do
  #get md5
  md5=$(echo $line | cut -c -32)

  #get path of file
  file=$( echo $line | cut -c  34-)

  #wenn datei existiert
  if [ -f "$file" ]; then
    # do nothing
    echo  > /dev/null
  else
    echo "rm $line"
    echo "$line" >> data_shares_Filme_RM
    sed -i "/$md5/d" data_shares_Filme
  fi

done

#search for new files
find /data/shares/Filme/ -type f | grep -v "/.Trash-" | grep -v '/data/shares/Filme/Clone' | grep -v '/data/shares/Filme/HandBrake'| sort | while read line; do
  #save fiel path
  result=$(grep "$line" data_shares_Filme); [ -z "$result" ] && {
    #wenn kein eintrag in liste...
    echo "new $line"
    result=$(md5sum "$line")
    echo $result >> data_shares_Filme_add
    result_md5=$(echo $result | cut -c -32)
    [ -f data_shares_Filme_RM ] && sed -i "/$result_md5/d" data_shares_Filme_RM
  }
done
[ -f data_shares_Filme_add ] && {
  cat data_shares_Filme_add >> data_shares_Filme
  rm data_shares_Filme_add
}

#sort & del dublicates
cat data_shares_Filme | sort -k 2 | uniq > data_shares_Filme_tmp
rm data_shares_Filme && mv data_shares_Filme_tmp data_shares_Filme

sed -i 's/\ \/data/\ \ \/data/g' data_shares_Filme
sed -i 's/\ \ \ \/data/\ \ \/data/g' data_shares_Filme
sed -i 's/\ \ \ \/data/\ \ \/data/g' data_shares_Filme
