#!/bin/sh
# This script takes an input directory and processes all files.
# It creates a directory structure in the output directory based
# on metadata of the file. The filename will also be created out
# of metadata, or replaced with the sha1 hash of itself in order
# to avoid duplicates.
usage() {
  print "Usage: autosort ";
  exit 2
}
# check input
test -d "$1" || usage
test -d "$2" || usage
# normalize relative paths
_indir="$(readlink -f "$1")"
_outdir="$(readlink -f "$2")"
####################
#   MAIN PROGRAM   #
####################
start(){
  # trigger main loop
  find "$_indir" -type f | while read _file;
  do
    # extract mime type
    local _mime="$(file -bi "$_file")"
    local _category=${_mime%%/*}
    local _type=${_mime##*/}
    case "$_category" in
      image) process_image "$_file" "$_type"; ;;
      *) printf 'Unhandled Category: %s in %s\n' "$_category" "$_file"; ;;
    esac
  done
}
#################
#   FUNCTIONS   #
#################
process_image() {
# $1 = file
# $2 = mime type
  case $2 in
    jpeg) handle_jpeg "$1"; ;;
    png) handle_jpeg "$1"; ;;
    gif) handle_copy "$1" "image" "$2"; ;;
    *) printf 'Unhandled Type: %s in %s\n' "$2" "$1"; ;;
  esac
}
handle_jpeg() {
# $1 = file
  local _exif="$(exifprint "$1")"
  local _make="$(printf '%s' "$_exif" | grep '0x010f' | awk '{for(i=5;i<=NF;++i)print $i}')"
  local _model="$(printf '%s' "$_exif" | grep '0x0110' | awk '{for(i=5;i<=NF;++i)print $i}')"
  local _datetime="$(printf '%s' "$_exif" | grep '0x9003' | awk '{for(i=5;i<=NF;++i)print $i}')"
  test -z "$_make" && local _make=unknown
  test -z "$_model" && local _model=unknown
  test -z "$_datetime" && local _datetime="$(sha1 -q "$1")"
  local _out="$(printf '%s %s/%s' "$_make" "$_model" "$_datetime" | tr '\n' ' ' | tr ':' '-')"
  install -bDm 0666 "$1" "$_outdir/${_out}.jpg" && rm -f "$1"
}
handle_copy() {
# $1 = file
# $2 = category
# $3 = type
  install -bDm 0666 "$1" "$_outdir/$2/$3/${1##*/}" && rm -f "$1"
}
start