#! /bin/bash

GDRIVE=/opt/midjourney/bin/gdrive
LOGFILE=/scratch/midjourney-sort-and-upload.log
MIDJOURNEYDIR=/midjourney/

echo ""
echo "Starting midjourney sync and upload - $(date)" 2>&1 | tee -a ${LOGFILE}

#if [[ ! -v SMALL ]]; then
#  echo "ERROR: No gdrive key for SMALL" 2>&1 | tee -a ${LOGFILE}
#  exit -1
#fi
#
#if [[ ! -v MEDIUM ]]; then
#  echo "ERROR: No gdrive key for MEDIUM" 2>&1 | tee -a ${LOGFILE}
#  exit -1
#fi
#
#if [[ ! -v LARGE ]]; then
#  echo "ERROR: No gdrive key for LARGE" 2>&1 | tee -a ${LOGFILE}
#  exit -1
#fi

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

(
if compgen -G "${MIDJOURNEYDIR}/images/*.png" > /dev/null; then
  echo New files. Sorting.
  for i in ${MIDJOURNEYDIR}/images/*.png; do
    maxdim=$(file "$i" | sed 's/,//g' | awk '{ print ($6 > $8)? $6 : $8 }')
    if [ $maxdim -lt 767 ]; then
      echo SMALL: "$i"
      rsync $i ${MIDJOURNEYDIR}/images.small/
      if [ $? -eq 0 ]; then
        mv $i ${MIDJOURNEYDIR}/images.filtered/
      fi
    elif [ $maxdim -lt 1281 ]; then
      echo MEDIUM: "$i"
      rsync $i ${MIDJOURNEYDIR}/images.medium/
      if [ $? -eq 0 ]; then
        mv $i ${MIDJOURNEYDIR}/images.filtered/
      fi
    else
      echo LARGE: "$i"
      rsync $i ${MIDJOURNEYDIR}/images.large/
      if [ $? -eq 0 ]; then
        mv $i ${MIDJOURNEYDIR}/images.filtered/
      fi
    fi
  done
else
  echo No new files. No need to sort.
fi
) 2>&1 | tee -a ${LOGFILE}

# As of 2023-07-21 we're no longer uploading to google drive
#echo Syncing Small 2>&1 | tee -a ${LOGFILE}
#${GDRIVE} sync upload --keep-largest ${MIDJOURNEYDIR}/images.small/ $SMALL 2>&1 | tee -a ${LOGFILE}
#echo Syncing Medium 2>&1 | tee -a ${LOGFILE}
#${GDRIVE} sync upload --keep-largest ${MIDJOURNEYDIR}/images.medium/ $MEDIUM 2>&1 | tee -a ${LOGFILE}
#echo Syncing Large 2>&1 | tee -a ${LOGFILE}
#${GDRIVE} sync upload --keep-largest ${MIDJOURNEYDIR}/images.large/ $LARGE 2>&1 | tee -a ${LOGFILE}

echo "Ending midjourney sync and upload - $(date)" 2>&1 | tee -a ${LOGFILE}
echo ""
