#!/bin/bash

# Checks for newer scripts version and downloads them

sdtdCommandUpdatescripts() {
	LOCAL=$(cat /usr/local/lib/7dtd/VERSION | grep "Version" | cut -d\  -f2)
	REMOTE=$(wget -qO- http://illy.bz/fi/7dtd/VERSION | grep "Version" | cut -d\  -f2)
	
	if [ $REMOTE -gt $LOCAL ]; then
		echo "A newer version of the scripts is available."
		echo "Local:     v.$LOCAL"
		echo "Available: v.$REMOTE"
		echo
		echo "Please check the release notes before continuing:"
		echo "  https://7dtd.illy.bz/wiki/Release%20Notes"
		echo
		
		while : ; do
			local CONTINUE
			read -p "Continue? (yn) " CONTINUE
			case $CONTINUE in
				y)
					echo "Updating..."
					break
					;;
				n)
					echo "Canceled"
					return
					;;
				*)
					echo "Wrong input"
			esac
		done
		
		wget -q http://illy.bz/fi/7dtd/management_scripts.tar.gz -O /tmp/management_scripts.tar.gz
		rm -Rf /usr/local/lib/7dtd /usr/local/bin/7dtd.sh
		tar --touch --no-overwrite-dir --exclude=etc/7dtd.conf --exclude=etc/cron.d --exclude=home -xzf /tmp/management_scripts.tar.gz -C /

		chown root.root /etc/init.d/7dtd.sh
		chown root.root /etc/bash_completion.d/7dtd
		chown root.root /usr/local/bin/7dtd.sh
		chown root.root /usr/local/lib/7dtd -R
		chmod 0755 /etc/init.d/7dtd.sh
		chmod 0755 /etc/bash_completion.d/7dtd
		chmod 0755 /usr/local/bin/7dtd.sh
		chmod 0755 /usr/local/lib/7dtd -R
		
		echo "Update done."
		echo
		echo "Note: This updated only script files. If the global config file"
		echo "/etc/7dtd.conf contains changes for the newer version or there"
		echo "were new files added to the user folder /home/sdtd those changes"
		echo "have not been applied!"
	else
		echo "Scripts are already at the newest version (v.$LOCAL)."
	fi
}

sdtdCommandUpdatescriptsHelp() {
	echo "Usage: $(basename $0) updatescripts"
	echo
	echo "Check for a newer version of the management scripts. If there is a newer"
	echo "version they can be updated by this command."
}

sdtdCommandUpdatescriptsDescription() {
	echo "Update these scripts"
}

