#!/bin/ksh
#
## Script pour générer une gallerie web à partir d'images
#  crée un fichier .md, convertit et transfère les images pour mon blog

# Définir le path des images dans la variable IMGPATH
#export IMGPATH="static/img"
#export BLOGPATH="/home/phil/www/philavelo"
#export POSTDIR="post"
export LOGFILE="/home/phil/test/img2hugopost"

conversion() {

filename=$1
file=$(basename "$filename")
extension="$(echo "$filename" | awk -F"." '{print $NF}')"
imgpath="$BLOGPATH/$IMGPATH"

# Valider qu'il s'agit d'une image JPEG
if [ $(echo $extension | grep -Ei "jpg|jpeg") ];
then
	cp "$filename" "$imgpath"
	# /home/phil/bin/opti "$imgpath/$file"

	# Add image blocks for images (log than process)
	echo "\n<a href=\"/img/$file\" data-lightbox=\"image-set\" data-title=\"caption\" data-alt=\"$ALT_TEXT\"><img src=\"/img/$file\" alt=\"\" /></a>" >> $LOGFILE
	echo "\n<a href=\"/img/$file\" data-lightbox=\"image-set\" data-title=\"caption\" data-alt=\"$ALT_TEXT\"><img src=\"/img/$file\" alt=\"\" /></a>" >> "$BLOGPATH/$POSTDIR/$POST_FILENAME"
else
	echo "$filename n'est pas une image"
fi
}

# Generate Hugo or plain post

# Get post name using zenity prompt
post_name=$(zenity --entry --text "Entrez le nom du fichier ou slug de l'article (sans espace):")
echo $post_name
export ALT_TEXT="$(echo $post_name | sed 's/-/ /g')"
cd $BLOGPATH

# Run Hugo new post command
export POST_FILENAME="$(date "+%Y-%m-%d")-$post_name.fr.md"
if [ $(echo $POSTDIR | grep -E 'content') ];
then
	# si Hugo retirer content/ du chemin
	POSTDIR2="$(echo $POSTDIR | sed 's/content\///')"
	echo "hugo new $POSTDIR2/$POST_FILENAME" >> $LOGFILE
	hugo new $POSTDIR2/$POST_FILENAME
else
	POSTDIR2=$POSTDIR
fi

echo "new file : $POST_FILENAME" >> $LOGFILE

# title or head of file
cat << 'EOF' >> "$BLOGPATH/$POSTDIR/$POST_FILENAME" 	
<head>
<link href="/css/lightbox.css" rel="stylesheet" />
<title>$ALT_TEXT</title>
</head>
Cliquer sur une image pour défiler.
EOF

# Traiter les images
for file in "$@" 
do
	conversion "$file" 
done

# tail of file
# script à la fin du <body>
cat << 'EOF' >> "$BLOGPATH/$POSTDIR/$POST_FILENAME" 	
<script src="/js/lightbox-plus-jquery.js"></script>
EOF
