#!/bin/sh
#
#  Copyright (c) 2021 by NuTyX team (http://nutyx.org)
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 
#  USA.
#
#

source /lib/lsb/init-functions

check_conf_exist()
{
	[ -f ${UPGRADE_HOME}/${UPGRADE_USER}${UPGRADE_CARDS_CONF} ] && return 0
	return 1
}
generate_conf()
{
	mkdir -p ${UPGRADE_HOME}/${UPGRADE_USER}/pkg/depot
	echo "
	
url http://download.nutyx.org

dir ${UPGRADE_HOME}/${UPGRADE_USER}${UPGRADE_DEPOT}/gui-extra
dir ${UPGRADE_HOME}/${UPGRADE_USER}${UPGRADE_DEPOT}/gui
dir ${UPGRADE_HOME}/${UPGRADE_USER}${UPGRADE_DEPOT}/cli-extra
dir ${UPGRADE_HOME}/${UPGRADE_USER}${UPGRADE_DEPOT}/cli
dir ${UPGRADE_HOME}/${UPGRADE_USER}${UPGRADE_DEPOT}/base
base ${UPGRADE_HOME}/${UPGRADE_USER}${UPGRADE_DEPOT}/base" > \
${UPGRADE_HOME}/${UPGRADE_USER}${UPGRADE_CARDS_CONF}
	chown -R ${UPGRADE_USER}:${UPGRADE_USER} ${UPGRADE_HOME}/${UPGRADE_USER}
}
download_only()
{
	check_conf_exist || generate_conf
	cards upgrade --download-only --conf=${UPGRADE_HOME}/${UPGRADE_USER}${UPGRADE_CARDS_CONF} \
	|| return 1
	return 0
}
download_ready()
{
	killproc $(which cards-upgrade-notifier)
	echo "UPGRADE_USER=$USER" > ${UPGRADE_READY}
	$(which cards-upgrade-notifier) ready
	return 0
}
main()
{
	if [ -z ${FCRONTAB_COMMAND} ];then
		echo "Please install 'fcron' package first !!!"
		exit 1
	fi
	if [ $UID -eq 0 ]; then
		[ -f ${UPGRADE_READY} ] || return 0
		source ${UPGRADE_READY}
		cards upgrade --no-sync --conf=${UPGRADE_HOME}/${UPGRADE_USER}${UPGRADE_CARDS_CONF} && \
		rm  -f ${UPGRADE_READY}
		chown -R  ${UPGRADE_USER}:${UPGRADE_USER} ${UPGRADE_HOME}/${UPGRADE_USER}${UPGRADE_DEPOT}
		exit 0
	else
		check_conf_exist || generate_conf
		download_only
		[ $(cards upgrade -c --conf=${UPGRADE_HOME}/${UPGRADE_USER}${UPGRADE_CARDS_CONF}) == "yes" ] && \
		download_ready
		exit 0
	fi
}

# Global variables
UPGRADE_USER=$USER
UPGRADE_HOME=/home
UPGRADE_CARDS_CONF=/pkg/cards.conf
UPGRADE_DEPOT=/pkg/depot
UPGRADE_READY=/tmp/.UPGRADE_READY
UPGRADE_UID="96"
FCRONTAB_COMMAND="$(which fcrontab)"
main "$@"
