#!/bin/bash
# ---------------------------------------------------------------------------
# This script is triggered by an udev-rule in /etc/udev/rules.d/99-usbcopy.rules.
# It copies all images from a SD-card to the hard-disk.
#
# Special features:
#   - rename files to a unique ID: pii123456.*
#   - copies to subdirs per day
#   - only copies files not already copied
#   - create thumbnails
#
# If DEBUG=1, messages go the the syslog. To view the messages, run
#   sudo journalctl SYSLOG_IDENTIFIER=copy_img2
#
# Dependencies: GraphicsMagick
#
# Author: Bernhard Bablok
# License: GPL3
#
# Website: https://github.com/bablokb/pi-imgtank
#
# ---------------------------------------------------------------------------

source $(dirname "$0")/copy_mv_img2.inc

# --- global settings   -----------------------------------------------------

setDefaults() {
  setGlobalDefaults
}

# --- check device   --------------------------------------------------------

checkDevice() {
  # query udev argument
  device="$1"
  msg "info: checking: $1"

}

# --- prepare system   -----------------------------------------------------

prepareSystem() {
  # change state of HAT: Action Start
  #/usr/local/sbin/hatctl.py AS

  # create IMAGE_ROOT (if it does not exist)
  if [ ! -d "$IMAGE_ROOT" ]; then
    mkdir -p "$IMAGE_ROOT"
    chown "$DATA_OWNER" "$IMAGE_ROOT"
  fi

  # create THUMB_ROOT (if it does not exist)
  if [ ! -d "$THUMB_ROOT" ]; then
    mkdir -p "$THUMB_ROOT"
    chown "$DATA_OWNER" "$THUMB_ROOT"
  fi

  # create mount-directory for SD-card
  mountdir="$DATA_ROOT/mnt_sd"
  msg "mountdir: $mountdir"
  mkdir -p "$mountdir"
  
  # try to mount SD-card (try /dev/sdx1 first, then fallback to /dev/sdx)
  local sd_device="/dev/${device}1"
  [ ! -b "$sd_device" ] && sd_device="/dev/${device}"
  if ! mount "$sd_device" "$mountdir"; then
    msg "error: could not mount $sd_device"
    cleanup
    exit 3
  fi
}

# --- cleanup   -------------------------------------------------------------

cleanup() {
  # umount SD-card
  msg "umounting mountdir: $mountdir"
  grep -q "$mountdir" /etc/mtab && umount "$mountdir"

  msg "Finished! Remove SDcard"
  
}

# --- copy all images   ----------------------------------------------------

copyFiles() {
  #cleanup display and show copy screen
  #python /home/pi/pi-imgtank/files/python-scripts/copy.py

  # check if timestamp-file exists on SD-card. If not, create it
  if [ ! -f "$mountdir/.last_img" ]; then
    touch -d "01/01/1960" "$mountdir/.last_img"
  fi

  # find all files newer than .last_img on SD-card and copy it
  local img srcStem srcStemNew targetStem ext
  for img in $(find "$mountdir/DCIM" \
                           -type f -newer "$mountdir/.last_img" | sort); do
    msg "processing $img"

    # check if we already copied a file with the same stem
    local srcStemNew="${img%.*}"
    if [ "$srcStem" != "$srcStemNew" ]; then
      # make the new stem the current stem
      srcStem="$srcStemNew"

      # query date of current image and create target directory
      local imgDate=$(getImageDate "$img")
      if [ ! -d "$IMAGE_ROOT/$imgDate" ]; then
        mkdir -p "$IMAGE_ROOT/$imgDate"
        chown "$DATA_OWNER" "$IMAGE_ROOT/$imgDate"
        mkdir -p "$THUMB_ROOT/$imgDate"
        chown "$DATA_OWNER" "$THUMB_ROOT/$imgDate"
      fi

      # get stem of target filename
      targetStem=$(nextNumber)
    fi

    # now copy image
    ext="${img##*.}"
    ext="${ext,,}"        # convert to lowercase
    msg "copying $img to $IMAGE_ROOT/$imgDate/$targetStem.$ext"
    cp -a "$img" "$IMAGE_ROOT/$imgDate/$targetStem.$ext"
    chmod -wx "$IMAGE_ROOT/$imgDate/$targetStem.$ext"
    chown "$DATA_OWNER" "$IMAGE_ROOT/$imgDate/$targetStem.$ext"

    # create thumbnail
    [ "$ext" = "jpg" ] && createThumb "$imgDate/$targetStem.$ext"
  done

  # save timestamp of last copied image
  if [ -f "$img" ]; then
    touch -r "$img" "$mountdir/.last_img"
  else
    msg "no images to copy"
  fi
}

# --- main program   ---------------------------------------------------------

setDefaults
checkDevice "$1"
prepareSystem
copyFiles
cleanup
