#!/bin/sh -e

# This script obtains the "real" location of my photos in the file system
# making *heavy* usage of locate and the internal knowledge about my very
# own folder structure.
#
# Before running this script do
#   sudo /usr/sbin/updatedb.plocate

FILELIST=0_files.txt

if [ -e "$FILELIST" ] ; then
  mv "$FILELIST" "${FILELIST}~"
fi

for i in *.jpg; do
  iyear=$(echo $i | sed 's/^\([12][90][0-9][0-9]\).\+$/\1/')
  isylvester=$(if echo $i | grep -q '^[12][90][0-9][0-9]1231' ; then echo 'y' ; else echo 'n' ; fi)
  for j in `locate $i | \
             grep -v \
                  -e '/home/andreas/bilder/sammlungen' \
                  -e '/home/andreas/public_html/' \
                  -e 'mgp/debian-med/img' \
                  -e 'bilder/pixum' \
                  -e '/home/andreas/texmf/tex' \
                  -e '/usr/local/share/' \
                  -e '\.jpg_$' \
                  -e '/bilder/other/' \
                  -e '/klein/' \
                  -e '/home/andreas/Downloads' \
                  -e '/home/cds/' \
                  -e '/web/' \
                  -e '/0web/' \
                  -e '/tmp-share/' \
                  -e '/0_fav/' \
                  -e '/20190419_klosterwanderweg_gut/' \
                  -e 'DebConf20@Home_' \
                  -e '/201710_herbst/'` \
           ; do
     if [ ! -L $j ] ; then
       # count number of '/' - probably the less nested dir is what we are seeking for
       # echo "$j $(echo $j | tr -d -c '/' | awk '{ print length; }')"
       jyear=$(echo $j | sed 's#^.\+/\([12][90][0-9][0-9]\)/.\+$#\1#')
       if [ $iyear -ge $jyear -o "$isylvester" = 'y' ] ; then
         echo "$j" >> "$FILELIST"
       fi
     fi
  done
done

for i in *.jpg; do
  if ! grep -q $i ${FILELIST} ; then
    iedit=$(echo $i | sed 's/\([^_]\)\.jpg/\1_.jpg/')
    if [ "$i" != "$iedit" ] ; then
      if [ "$(locate $iedit)" != "" ] ; then
        echo "Bild $i wurde editiert und heißt nun $iedit."
      fi
    fi
  fi
done

ni=$(ls *.jpg | wc -l)
nl=$(cat "$FILELIST" | wc -l)

if [ $ni -ne $nl ] ; then
  echo "Number of images in dir: $ni"
  echo "Number of lines in "$FILELIST": $nl"
  exit 1
fi
