#!/bin/bash

# simple sfs manager for fatdog 
# originally written by 01micko 120618, i18n by L18L 131113
# completely rewritten by SFR 170116
# requires: gtkdialog, Xdialog, bash, wget, load_sfs.sh

set -a
set -o pipefail

# std localisation stanza
export TEXTDOMAIN=fatdog
. gettext.sh

APPNAME="$(gettext 'SFS Manager')"

[ $(id -u) -ne 0 ] && exec gtksu "$APPNAME" "$0" "$@"

# -----------------------------------------------------------------------------

#URLs
URL_IBIBLIO="http://distro.ibiblio.org/pub/linux/distributions/fatdog"	# default
URL_AARNET="http://mirror.aarnet.edu.au/pub/fatdog"
URL_UOC="http://ftp.cc.uoc.gr/mirrors/linux/fatdog"
URL_NLUUG="http://ftp.nluug.nl/ibiblio/distributions/fatdog"

VERSION="$(< /etc/fatdog-version)"
VERSION=${VERSION%?}0 # replace last digit with zero (70x becomes 700, 71x becomes 710, etc)
#SFSDEST="$(readlink /mnt/home)" # DVD saves is okay - it has /mnt/home symlink
SFSDEST="/mnt/home"					# consistent with load_sfs.sh's default path
[ "$SFSDEST" ] || SFSDEST="$HOME"	# no savefile, save to $HOME

WORKDIR="/tmp/sfsmanager.${USER}.$$"
mkdir -p "$WORKDIR"
trap 'rm -rf "$WORKDIR"; exit' 0 INT HUP TERM QUIT ABRT

# -----------------------------------------------------------------------------

# 1-type, 2-message
func_msg () {
	case "$1" in
		yesno_error)	Xdialog --stdout --title "$APPNAME" \
						--icon /usr/share/pixmaps/midi-icons/error.xpm \
						--yesno "$2" 0 0
		;;
		yesno_info_chk)	Xdialog --stdout --title "$APPNAME" \
						--icon /usr/share/pixmaps/midi-icons/question.xpm \
						--check "$3" "$4" \
						--yesno "$2" 0 0
		;;
		error)			Xdialog --stdout --title "$APPNAME" \
						--icon /usr/share/pixmaps/midi-icons/error.xpm \
						--msgbox "$2" 0 0
		;;
		splash)			Xdialog --stdout --title "$APPNAME" \
						--no-buttons \
						--infobox "$2" 0 0 999999999 &	# to the background
		;;
		gauge)			Xdialog --stdout --title "$APPNAME" \
						--icon /usr/share/pixmaps/midi-icons/update48.png \
						--gauge "$2" 0 0
		;;
		info|*)			Xdialog --stdout --title "$APPNAME" \
						--icon /usr/share/pixmaps/midi-icons/lamp48.png \
						--msgbox "$2" 0 0
		;;
	esac
}

# -----------------------------------------------------------------------------

func_getlist () {
	#splash
	func_msg splash "$(gettext 'Please wait, downloading SFS list.')"
	XPID=$!
	
	#get the lists
	#curl -Ls "${URL_IBIBLIO}/sfs/${VERSION}/sfslist" | sed -e 's/.sfs|[a-fA-F0-9]\+//g' -e 's/$/|'$(gettext "Official")'/g'	> "${WORKDIR}/sfslist"
	wget -q -O - "${URL_IBIBLIO}/sfs/${VERSION}/sfslist" | sed -e 's/.sfs|[a-fA-F0-9]\+//g' -e 's/$/|'$(gettext "Official")'/g'	> "${WORKDIR}/sfslist"
	RET=$?
	#curl -Ls "${URL_IBIBLIO}/contrib/sfs/${VERSION}/sfslist" | sed -e 's/.sfs|[a-fA-F0-9]\+//g' -e 's/$/|'$(gettext "Contrib")'/g'	>> "${WORKDIR}/sfslist"
	wget -q -O - "${URL_IBIBLIO}/contrib/sfs/${VERSION}/sfslist" | sed -e 's/.sfs|[a-fA-F0-9]\+//g' -e 's/$/|'$(gettext "Contrib")'/g'	>> "${WORKDIR}/sfslist"
	RET=$((RET+$?))
	
	#kill splash
	kill -0 $XPID 2>/dev/null && kill $XPID
	
	if [ ${RET} -ne 0 ]; then
		func_msg error "$(gettext 'Failed to download SFS list.\nCheck your internet connection.')"
		exit 1
	fi
}

# -----------------------------------------------------------------------------

func_getsfs () {
	#repos
	case "$REPO" in
		"AARNET"*)
			URL_OFFICIAL="${URL_AARNET}/sfs/${VERSION}/"
			URL_CONTRIB="${URL_AARNET}/contrib/sfs/${VERSION}/"
		;;
		"UOC"*)
			URL_OFFICIAL="${URL_UOC}/sfs/${VERSION}/"
			URL_CONTRIB="${URL_UOC}/contrib/sfs/${VERSION}/"
		;;
		"NLUUG"*)
			URL_OFFICIAL="${URL_NLUUG}/sfs/${VERSION}/"
			URL_CONTRIB="${URL_NLUUG}/contrib/sfs/${VERSION}/"
		;;
		"Ibiblio"*|*)
			URL_OFFICIAL="${URL_IBIBLIO}/sfs/${VERSION}/"
			URL_CONTRIB="${URL_IBIBLIO}/contrib/sfs/${VERSION}/"
		;;
    esac

	mkdir -p "$SFSDEST"

	# Download selected SFSes one by one
	for SFS in $SFSCHOICE; do
		# check if SFS is already in SFSDEST
		if [ -e "${SFSDEST}/${SFS}.sfs" ]; then
			func_msg error "$(eval_gettext 'Aborted, ${SFS}.sfs already exists in ${SFSDEST}.')"
			continue
		fi
		
		# set repo
		case "$(grep -m 1 "^${SFS}|" "${WORKDIR}/sfslist" | cut -f4 -d '|')" in
			"$(gettext 'Contrib')")	URL="${URL_CONTRIB}"	;;
			*)						URL="${URL_OFFICIAL}"	;;
		esac
		
		#download checksum
		#CHECKSUM="$(curl -Ls ${URL}/${SFS}.sfs.md5sum.txt | cut -d ' ' -f1)"
		CHECKSUM="$(wget -q -O - ${URL}/${SFS}.sfs.md5sum.txt | cut -d ' ' -f1)"
		[ $? -ne 0 ] && func_msg error "$(eval_gettext 'Failed to download ${SFS}.sfs checksum.')" && continue
		
		#download SFS
		# Closing rxvt while downloading is in progress dumps a wget-log
		# file in CWD unless "-o/dev/null --show-progress" is passed to wget.
		# SFR: "-o/dev/stdin" fixes the 'wget-log' problem without reducing the verbosity.
		#rxvt -background grey20 -foreground white -title "$(eval_gettext 'Downloading ${SFS}.sfs')" -geometry 80x8  \
		#	 -e wget -o/dev/stdin --show-progres -t0 --waitretry=5 -4 -P "${SFSDEST}" -c "${URL}/${SFS}.sfs"
		# SFR: problem - after closing rxvt, wget still works in the background
		# SFR: let's do it using Xdialog's gauge instead:
		wget -t0 --waitretry=5 -4 -P "${SFSDEST}" -c "${URL}/${SFS}.sfs" 2>&1 | \
			stdbuf -o0 sed -n 's/.* \([0-9]\+\)%.*/\1/p' 2>/dev/null | \
			func_msg gauge "$(eval_gettext 'Downloading ${SFS}.sfs')"
		
		if [ $? -ne 0 ]; then
			rm -f "${SFSDEST}/${SFS}.sfs"
			func_msg error "$(eval_gettext 'Download aborted!')"
			continue
		fi
		
		#compare checksums
		if [ -f "${SFSDEST}/${SFS}.sfs" ]; then
			if [ "$(md5sum "${SFSDEST}/${SFS}.sfs" | cut -d ' ' -f1)" != "$CHECKSUM" ];then
				func_msg yesno_error "$(eval_gettext 'MD5 checksum of ${SFS}.sfs is incorrect.\nKeep it anyway? If you click "No" the SFS will be deleted.')"
				[ $? -ne 0 ] && rm -f "${SFSDEST}/${SFS}.sfs" && continue
			fi
		else
			func_msg error "$(eval_gettext 'Failed to download ${SFS}.sfs.')"
			continue
		fi
		
		#ask to load the SFS
		RET="$(func_msg yesno_info_chk "$(gettext 'File correctly downloaded and MD5 checked.')\n$(eval_gettext 'Do you want to load ${SFS}.sfs now?')" \
								"$(gettext 'Check this box to load this SFS at every boot.')" false)"
		[ $? -ne 0 ] && continue
		
		#check if SFS is already loaded
		CHECKSFS="$(load_sfs.sh --loaded | grep -m 1 "/${SFS}.sfs")"
		CHECKSFS_FILE="${CHECKSFS##*/}"
		CHECKSFS_PATH="${CHECKSFS%/*}"
		if [ "${CHECKSFS_FILE}" = "${SFS}.sfs" ]; then
			func_msg error "$(eval_gettext 'Another ${SFS}.sfs is already loaded\nfrom directory: ${CHECKSFS_PATH}.')"
			continue
		fi
		
		#load it
		load_sfs.sh --load "${SFSDEST}/${SFS}.sfs"
		[ "$RET" = "checked" ] && load_sfs.sh --add  "${SFSDEST}/${SFS}.sfs"
	done
}

# -----------------------------------------------------------------------------

func_gui () {
	export choice='<window title="'${APPNAME}'" window-position="1" image-name="/usr/share/pixmaps/midi-icons/squashfs-image48.png">
	<vbox>
		<hbox>
		
		<hbox space-fill="false" space-expand="false">
			<text><label>'$(gettext "Choose your download site:")' </label></text>
			<comboboxtext>
				<variable>REPO</variable>
				<item>Ibiblio ('$(gettext "USA")')</item>
				<item>AARNET ('$(gettext "Australia")')</item>
				<item>UOC ('$(gettext "Greece")')</item>
				<item>NLUUG ('$(gettext "Netherlands")')</item>
			</comboboxtext>
		</hbox>
	
		<text space-fill="true" space-expand="true"><label>""</label></text>
		<vseparator></vseparator>
		<text space-fill="true" space-expand="true"><label>""</label></text>
		
		<text><label>'$(gettext "Save SFS files to:")' </label></text>
		<hbox>
			<entry fs-action="folder" fs-folder="'${SFSDEST}'" fs-title="'$(gettext "Select an existing folder")'">
				<variable>SFSDEST</variable>
				<default>'"${SFSDEST}"'</default>
			</entry>
			<button>
				<input file stock="gtk-directory"></input>
				<action>fileselect:SFSDEST</action>
			</button>	
		</hbox>
	
		</hbox>
	
		<hseparator></hseparator>
	
		<text><label>'"$(gettext "These are the SFS files available for download"):"'</label></text>
		<tree auto-sort="true" column-type="string|int64" selection-mode="3" column-sizing="0|0|300|0" rules-hint="true">
			<label>'$(gettext "File name")'|'$(gettext "Size (MB)")'|'$(gettext "Description")'|'$(gettext "Repository")'</label>
			<variable>SFSCHOICE</variable>
			<input file>'"${WORKDIR}/sfslist"'</input>
			<action>func_getsfs</action>
			<action signal="button-release-event">enable:DL_BUTTON</action>
			<action signal="key-release-event">enable:DL_BUTTON</action>
			<action signal="button-release-event" condition="command_is_true( [ \"${SFSCHOICE}\" = \"\" ] && echo true)">disable:DL_BUTTON</action>
			<action signal="key-release-event" condition="command_is_true( [ \"${SFSCHOICE}\" = \"\" ] && echo true)">disable:DL_BUTTON</action>
		</tree>
		
		<hbox>
		<button space-fill="false" space-expand="false">
		  <label>'$(gettext "System SFS Loader")'</label>
		  <input file>/usr/share/midi-icons/squashfs-image48.png</input>
		  <height>24</height>
		  <action>load_sfs.sh &</action>
		</button>
		
		<text space-fill="true" space-expand="true"><label>""</label></text>
		
		<button sensitive="false">
			<variable>DL_BUTTON</variable>
			<label>'$(gettext "Download selected")'</label>
			<input file stock="gtk-goto-bottom"></input>
			<action>func_getsfs</action>
		</button>
		<button>
			<label>'$(gettext "Quit")'</label>
			<input file stock="gtk-quit"></input>
			<action>exit:exit</action>
		</button>
		</hbox>
		
	</vbox>
	</window>'

	gtkdialog -p choice -G 750x380
}

# =============================================================================

### START ###

func_getlist
func_gui

#END
