#!/bin/sh

_imgpath="$(readlink -f "${*}")"
_imgname="$(basename "$_imgpath")"

edit_template() {
    [ ! -f "$1" ] \
        && echo "<p></p>" > "$1"
    vim "$1"
}

error_exit() {
    echo "$1"
    read
    exit 1
}

if [ -z "${_imgpath}" ]
then
    echo "Could not read image path: $1"
    read
fi

_names="\
$(exiftool -q -q -p '$modifyDate' -p '$createDate' -p '$dateTimeOriginal' "${_imgpath}" | tr ':' '-' | tr ' ' '_')
$(basename "$(dirname "${_imgpath}")")
${_imgname%%.*}
_custom
$(date +"%Y-%m-%d_%H-%M-%S")"

_name="$( echo "$_names" \
            | sort -u \
            | fzf --prompt="Filename> " \
                || error_exit "fzf on name selection failed")"

if [ "${_name}" == "_custom" ]
then
    echo "$_names"
    echo -n "Filename (without extension): "
    read -r _name
fi

[ -z "${_name}" ] \
    && error_exit "Filename not set"

cd "${HOME}/website/photos"

gallerydir="$((echo NEW; find * -mindepth 0 -maxdepth 0 -type d; ) \
                | fzf --prompt "Directory> " \
                    || error_exit "Directory not set after fzf")"

if [ "${gallerydir}" == "NEW" ]
then

    echo -n "Add new gallery name ($(date +"%Y-%m-%d_")): "
    read -r gallerydir

    [ -z "${gallerydir}" ] \
        && error_exit "New directory requested, but not set"

    mkdir -p "${gallerydir}"

    echo -n "Add gallery description [y/N]: "
    read -r gallerydescr

    case "${gallerydescr}" in
        [yY]) edit_template "${gallerydir}/index.txt"; ;;
    esac

fi

[ -z "${gallerydir}" ] \
    && error_exit "Directory not set"

_mime="$(file -ib "${_imgpath}")"
if [ "${_mime}" == "image/jpeg" ]
then
    cp "${_imgpath}" "${gallerydir}/${_name}.jpg"
else
    convert "${_imgpath}" "${gallerydir}/${_name}.jpg"
fi

jhead -q -autorot "${gallerydir}/${_name}.jpg"
jpegoptim -w 12 --all-progressive --strip-all "$gallerydir/${_name}.jpg"

echo -n "Add image description? [y/N]: "
read -r imagedescr

case "$imagedescr" in
    [yY]) edit_template "${gallerydir}/${_name}.txt"; ;;
esac

cd "${HOME}/website/photos"
git pull
find . -type f \
    -not -name "*.html" \
    -not -path "*/mid/*" \
    -not -path "*/thm/*" \
    -exec git add {} +
git commit -m "Adding ${_name} to ${gallerydir}"
git push

echo -n "Regenerate Website? [y/N]: "
read -r regen

case $regen in
    [yY]) cd ~/website && make; ;;
esac

echo
echo "https://stefanhagen.de/photos/${gallerydir}/${_name}.html"
echo

read
