#!/bin/bash
# +SPDX:MIT

## WE NEED SOME DEPENDENCIES
depcheck() {
	if ! command -v "$1" &> /dev/null ; then
		echo "Missing dependency $1"
		exit 1
	fi
}
depcheck file
depcheck find
depcheck fzf

## Find the users Pictures Directory
# The order of precedence is as follows
# 1. GSCRIPTS_PICTURES
# 2. XDG_PICTURES_DIR
# 3. HOME/Pictures
if command -v "xdg-user-dir" &> /dev/null; then
	XDG_PICTURES_DIR="$(xdg-user-dir PICTURES)"
	# this is the proper way of getting this directory
	# according to the xdg specs
fi
PICTURESDIR=${GSCRIPTS_PICTURES:-${XDG_PICTURES_DIR:-${HOME}/Pictures}}

# This would be a rare occurance but we must be safe
if [[ ! -e ${PICTURESDIR} ]] ; then
	echo "Could not find ${PICTURESDIR}" >&2
	echo "Ensure it exists and or check your environment"
fi

# TODO: Make this nice e.g Read the existing folders and present a choice..
# or at least store the last used name as a variable
read -e -p"Camera Name>" CAMERA_NAME

# In the event the user is an idiot we just do this.
if [[ -z ${CAMERA_NAME} ]]; then
	CAMERA_NAME="Unknown"
fi
CAMERA_NAME=$(tr "[:space:]" "_" <<< "$CAMERA_NAME")

## After this we need to find all the image files in the current directory
declare -a ALL_FILES
declare -a IMAGES
# To avoid using xargs later we read all the files into an array
readarray -d '' ALL_FILES < <(find . -type f -print0)

for FILE in "${ALL_FILES[@]}"
do
	# Then manually check via this loop if its an image
	if [[ "$(file --mime-type "$FILE")" =~ .*image/.* ]]; then
		# Before constructing our actual images array
		IMAGES+=("$FILE")
	fi
done

echo "Found the Following images"
printf '%s\n' "${IMAGES[@]}"

# Make sure everything is cool
echo "Do you want to import them to your computer"
# TODO: make this a little better UX
read -r -p"y/N" -n1 CONFIRM
if [[ "$CONFIRM" != "y" ]]; then
	exit 0
fi
echo ""


## Using the Information from before create our import folder
CAMERA_ROOT="${PICTURESDIR}/${CAMERA_NAME}"
IMPORT_FOLDER="${CAMERA_ROOT}/$(date -I | tr '-' '/')"
mkdir -p "$IMPORT_FOLDER"

## Then we safely copy the images into the folder.
# TODO: Perhaps this can now be made more parallel safely?
for FILE in "${IMAGES[@]}"
do
	echo "$FILE"
	cp -iv -t "$IMPORT_FOLDER" "$FILE"
done
