#!/bin/sh

IHM_affiche_for_zenity() {

	texte="<b>Application :\t<big>$1</big></b>\n
<span>Résumé :\t$2</span>\n
<span>Éditeur :\t$3</span>$4\n
<span>Licence :\t$5</span>\n
<span>Description :</span>\n
<span>$6</span>"
	
	"$7" --question \
	       --no-wrap \
	       --title="Snap : installer $1 via son paquet snap ?" \
	       --ok-label="Installer $1" --cancel-label="Ne pas installer" --text "$texte" $8
}

IHM_affiche() {
	if command -v yad > /dev/null; then
		dialogUI=yad
		additionalArgs="--center --image=download"
	elif command -v zenity > /dev/null; then
		dialogUI=zenity
	else
		echo "la commande zenity n'existe pas."
		echo "Aucun autre moyen implémenté pour avoir une fenêtre de dialogue"
		exit 1
	fi
	
	IHM_affiche_for_zenity "$1" "$2" "$3" "$4" "$5" "$6" "$dialogUI" "$additionalArgs"

}

get_infos() {
	echo "$1" | grep -m1 "$2:" | cut -d':' -f2- | awk '{$1=$1};1'
}

# on vérifie qu'il y a un nom de programme en argument
[ -z "$1" ] && exit 1

# récupérer le programme
progName=$(echo "$1" | sed "s/snap:\/\///g")

# on récupère les informations de snap info pour ce programme

informations=$(LANG=C snap info --unicode=always "$progName" 2>&1)

if echo "$informations" | grep -qF "no snap found"; then
	zenity --warning --no-wrap --title="Aucun snap pour $1" --text="$informations"
	exit 1
fi

prog_name=$(get_infos "$informations" 'name')
summary=$(get_infos "$informations" 'summary')
publisher=$(get_infos "$informations" 'publisher')

# store_url=$(get_infos "$informations" 'store-url')
# contact_publisher=$(get_infos "$informations" 'contact')
license=$(get_infos "$informations" 'license')

# on commence avec p = 0 donc false (on affiche pas)
# quand on trouve un ligne commençant par description:, on affiche
# on n'affiche plus si on tombe sur une ligne respectant l'expression "^.+:"
description=$(echo "$informations" | awk 'BEGIN {p=0};
     /^description:/ { p = 1 ; next };
     /^.+:/ { p = 0 ; next};
     p { print }')

#echo "progname : $prog_name"
#echo "summary : $summary"
#echo "publisher : $publisher"
#echo "store : $store_url"
#echo "contact : $contact_publisher"
#echo "license : $license"
#echo "desc : $description"

 # vrai si l'éditeur est de confiance selon la sortie de snap info
spanTickPublisherTrusted=""
if echo "$publisher" | grep -Fq "✓"; then
	spanTickPublisherTrusted='<b><span color="green">✓</span></b>'
	publisher=$(echo "$publisher" | tr -d '✓')
fi


if IHM_affiche "$prog_name" "$summary" "$publisher" "$spanTickPublisherTrusted" "$license" "$description"; then
	# pkexec pour une demande graphique
	pkexec snap install "$prog_name"
fi

# sinon ne rien faire