#!/bin/bash

# Copyright 2016-2020  Jay Flood, SP, Brasil
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Author: brokenman@porteus.org
#
# This is a script to download Porteus bundles

# Source some functions
. /usr/share/porteus/porteus-functions
. /usr/share/porteus/gtkdialog-functions

txtsize(){
echo '<text use-markup="true" default-width="'$1'"><label>"<span size='"'$2'"' weight='"'$3'"'>'$4'</span>"</label></text>'
}

# Export/set some variables
export SCRIPT="$(cd "${0%/*}" 2>/dev/null; echo "$PWD"/"${0##*/}")"
TMPDIR=/tmp/.bundle.$$
SERVER=`awk -F= '/^SERVER=/{print$NF}' /etc/porteus.conf`
[ `uname -m` != "x86_64" ] && ARCH=i586 || ARCH=x86_64
CWD=`pwd`
PVER=`< /etc/porteus-version`
BUNDLES=$SERVER/$ARCH/$PVER/bundles
get_desktop ## Returns DESKTOP=<lowercasedesktop>

cleanup(){
rm -rf $TMPDIR 2>/dev/null
exit	
}

fail_abort(){
gtk_message "There was a problem" "$1" "$2" gtk-dialog-warning 500
cleanup
}

# Check for porteus
if ! is_porteus; then
	fail_abort "This script can only run on Porteus." \
	"You can changes this by editing $SCRIPT line number: $LINENO"
fi

# Check for modules diretory
if [ "$MODDIR" ]; then
	if ! is_writable $MODDIR; then
		TARGETDIR=/tmp
			else
		export TARGETDIR=$MODDIR
	fi
else
	TARGETDIR=/tmp
fi

############# START WORK
mkdir $TMPDIR && cd $_
wget $BUNDLES/
if [ ! -e index.html ]; then
	cd -
	fail_abort "Could not download the bundle list." \
	"$SERVER"
else
	if ! grep -q xzm index.html; then
		cd -
		fail_abort "Bundle list does not contain modules."
		"$SERVER"
			else
		RESULT=`grep -o '<a href=['"'"'"][^"'"'"']*['"'"'"]' index.html | \
		sed -e 's/^<a href=["'"'"']//' -e 's/["'"'"']$//' | \
		egrep "$ARCH|alldesktops" | egrep "$DESKTOP|alldesktops" | egrep ".xzm"`
		fi
fi
cd -

export MAIN_BUNDLES='
<window title="Porteus bundles" icon-name="cdr">
<vbox>
<hbox>
      <pixmap icon_size="5" icon-name="cdr">
      </pixmap>
	'`txtsize 400 x-large normal "  Porteus bundles downloader"`'
	'`hsep`'
</hbox>
	<frame>
		<tree selection-mode="3" exported-column="0" rules-hint="true" headers-clickable="false">
			<label>Module</label>
			<variable>MOD</variable>
			<width>400</width>
			<height>300</height>
			'`for a in $RESULT; do
				echo "<item>$a</item>"
			done`'
		</tree>
	</frame>
<hbox>
	'`butok`'
	'`butcancel`'
</hbox>
</vbox>
</window>
'
gtkdialog -p MAIN_BUNDLES > $TMPDIR/dump

## Check for cancel
if [[ `egrep "Cancel|abort" $TMPDIR/dump` ]]; then
	cleanup
fi
MOD=`awk -F'"' '/^MOD=/{print$2}' $TMPDIR/dump`

## Check for valid link
! grep "\.xzm" <<<$MOD && fail_abort "You must click on a package to download." "Exiting"
LINK=$BUNDLES/$MOD

## Download file
cd $TARGETDIR
gtk_download $LINK

SUM1=`lynx -dump -dont_wrap_pre $SERVER/$ARCH/$PVER/bundles/md5sums.txt | grep $MOD | cut -d" " -f1`
SUM2=`md5sum $MOD | cut -d" " -f1`
gtk_infobox "Verifying download integrity.." "500"
if [ "$SUM1" = "$SUM2" ]; then 
    gtk_message2 "Checksum match." "Module verified." 
else 
    gtk_message "Checksum Mismatch!" "Integrity check failed! Possible Corrupt Module!" "You may want to delete the module in $TARGETDIR and try again."
    cleanup
fi
 
cd -

if [ "$TARGETDIR" = /tmp ]; then
	gtk_message "Module downloaded" "Your module is in /tmp" "Please move the module to your modules directory to persist a reboot." gtk-yes 500
else
	gtk_message "Module downloaded" "Your module is in '$TARGETDIR'" "The module will be activated each time you boot." gtk-yes 500
fi

## Ask if user wants to activate now
for STATEMENTS in  $(gtk_yesno "Module activation" "Would you like to activate the module now?" |gtkdialog -s); do 
	eval $STATEMENTS 
	if grep -qo Yes<<<$STATEMENTS; then
		activate $TARGETDIR/$MOD
	fi
done

cleanup
