#!/bin/sh
# ============================================================================
#
# This file is part of the 'FFP zypkg'
# http://zyxel.nas-central.org/wiki/FFP_as_zypkg
#
# 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, 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.
#
# Author: Mijzelf <Mijzelf@live.com>
#
# ============================================================================
PKGNAME="ffp"
PKG_ROOT="/usr/local/zy-pkgs"
ADMIN_DIR="/i-data/md0/admin"
CONFIG_DIR="${PKG_ROOT}/config/${PKGNAME}"
CONFIG_FILE="${CONFIG_DIR}/config"
FFPROOT=${PKG_ROOT}/ffproot
SCRIPTVERSION=20171126

# main start

######################################
## Find the IP address of the box
FrameworkGetIPAddress()
{
	# Detect interfaces
	local interfaces=` ifconfig | grep -e "^egiga" -e "^bond" -e "^eth" | cut -d ' ' -f 1 `

	# And find the IP (v4) address
	for interface in $interfaces
	do
		local address=` ifconfig ${interface} | grep "inet addr" | tr -s ' ' `
		if [ "${address}" != "" ] ; then
			echo ${address} | cut -d ' ' -f 2 | cut -d ':' -f 2
			return
		fi
	done
	hostname # What else?
}

#####################################
## Echo the URL of the package
FrameworkGetLink()
{
	# Do we have a webinterface at all?
	[ ! -d ${PKG_ROOT}/gui/${PKGNAME}/ ] && exit 0

	local address=` FrameworkGetIPAddress `

	# Seach for configured ports
	local ports=
	for directory in /etc/pkg_service_conf /etc/service_conf
	do
		[ ! -d ${directory} ] && continue

		ports=` grep "^Listen" ${directory}/httpd_zld*.conf | awk '{ print $2 }' `
		ports="$ports ` grep "^<VirtualHost" ${directory}/httpd_zld*.conf | cut -d ':' -f 2 | cut -d '>' -f 1 `"
		ports=` echo $ports | tr -s ' ' | tr ' ' '\n' | sort | uniq | grep -v 8082 `
		break
	done

	for port in $ports
	do
		# Find out if it's https:
		protocol=http
		defaultport=80
		grep -i "^<VirtualHost.*${port}" -A 50 ${directory}/httpd_zld*.conf >/tmp/.$$.${PKGNAME}

		while read line
		do
			if echo $line | grep -i "^</VirtualHost" >/dev/null
			then
				break
			fi

			if echo $line | grep -i "SSLEngine *On" >/dev/null
			then
				protocol=https
				defaultport=443
			fi
		done </tmp/.$$.${PKGNAME}
		rm /tmp/.$$.${PKGNAME}

		[ ${defaultport} -eq 443 ] && continue # Package manager crashes on https :$


		[ $port -eq $defaultport ] && port="" || port=":${port}"

		local url="${protocol}://${address}${port}/pkg/${PKGNAME}/"

		echo  $url
		# We can only output a single url
		return
	done
}



GetLink()
{
	FrameworkGetLink
}

Status()
{
    if [ ! -f ${CONFIG_FILE} ] ; then
        mkdir -p ${CONFIG_DIR}
        echo "Disabled" >${CONFIG_FILE}
    fi
    cat ${CONFIG_FILE}
}

# ========================================
# function RotateLogfile
# Arguments: directory logfile
# Rotates logfile, compresses old versions
# ========================================
RotateLogfile()
{
    logdir=$1
    logfile=$2
    logpath=${logdir}/${logfile}

    echo Rotating logfiles...
    oldlog=${logpath}.9.gz
    if [ -r ${oldlog} ] ; then
        echo rm ${oldlog}
        rm ${oldlog}
    fi

    for nr in 8 7 6 5 4 3 2 1
    do
        oldlog=${logpath}.${nr}.gz
        if [ -r ${oldlog} ] ; then
	    newnr=`expr $nr + 1`
	    newlog=${logpath}.${newnr}.gz
	    echo mv ${oldlog} ${newlog}
	    mv ${oldlog} ${newlog}
	fi
    done
    
    if [ -r ${logpath} ] ; then
	echo "cat ${logpath} | gzip -c >${oldlog}"
	cat ${logpath} | gzip -c >${oldlog}
	rm ${logpath}
    fi
}

# ===================================================
# function FindInDatabase
# Find first argument in list. Return next item
# Arguments: $1 search item
#            rest is database
# Output
FOUNDENTRY=""
# ===================================================
FindInDatabase()
{
	if [ "$1" = "" ] ; then
		return 2
	fi
                    
	SEARCHFOR=$1
	FOUNDENTRY=""
                                
	shift
	while [ "$1" != "" ] ; 
	do
		if [ "$1" = "${SEARCHFOR}" ] ; then
			FOUNDENTRY=$2
			return 0
		fi
		shift ; shift
	done
                                                                   
	return 1
}
# ==================================================
# function GetNasType
# Try to find out the NAS type, and FW
NASTYPE="" # output NAS type
FIRMWARE="" # output FW
# ===================================================
GetNasType()
{
    models="D401 NSA210 \
        D501 NSA220 \
        DC01 NSA221 \
        DA01 NSA310_TDC \
        A203 NSA310_ZyXEL \
        DD01 NSA320 \
        AA03 NSA325 \
        A403 STG100 \
        A803 STG211 \
        AB03 STG212 \
        AE03 NSA325v2 \
        AD03 NSA310s \
        AF03 NSA320s \
        B103 NAS540 \
        B203 NAS520 \
	B403 NAS542 \
        "
                   
	echo Try to determine NAS type...
                                                                                
	if [ "" = "${NASTYPE}" ] ; then
		for file in /zyxel/mnt/info/modelid /firmware/mnt/info/modelid
		do
			if [ -r ${file} ] ; then
			    model=` cat ${file} `
			    echo -n "according to ${file}: ${model}->"
			    if FindInDatabase ${model} ${models} ;
			    then
				NASTYPE=${FOUNDENTRY}
				echo ${NASTYPE}
			    else
				echo Unknown
			    fi
			fi
		done
	fi

	if [ "" = "${NASTYPE}" ] ; then
		kernel=` uname -r `
		echo -n "according to uname -r: ${kernel}->"
		case ${kernel} in
			2.6.18.6*)
				NASTYPE=NSA220
				;;
			2.6.24.4*)
				NASTYPE=NSA210
				;;
			*)
				NASTYPE=Unknown-${model}
				;;
		esac
		echo ${NASTYPE}
	fi

	for file in /zyxel/mnt/info/fwversion /firmware/mnt/info/fwversion /etc/fwversion
	do
		if [ -r ${file} ] ; then
			FIRMWARE=` cat ${file} `
			break
		fi
	done
                                       
	if [ "" = "${FIRMWARE}" ]; then
		FIRMWARE="Undetermined"
	fi

	NASTYPE=` echo "${NASTYPE}" | tr -d '"' | tr -d "'" `
	FIRMWARE=` echo "${FIRMWARE}" | tr -d '"' | tr -d "'" `

	echo type ${NASTYPE}, fw ${FIRMWARE}
}

Startup()
{
    STATUS=` Status `
    if [ "$STATUS" = "Enabled" ] ; then 
	exec >>/tmp/_ffp.log 2>&1
	local logroot=${ADMIN_DIR}/zy-pkgs/ffp
	mkdir -p $logroot
	RotateLogfile $logroot ffp.log
	exec >>/dev/null 2>&1
	mv /tmp/_ffp.log $logroot/ffp.log
	exec >>$logroot/ffp.log 2>&1
	GetNasType
	${FFPROOT}/after_booting.sh StartFFP -t zypkg -n "${NASTYPE}" -f "${FIRMWARE}"

        local httpdconf=/etc/pkg_service_conf
        if [ -d ${httpdconf} ] ; then
                echo Alias /pkg/${PKGNAME} ${PKG_ROOT}/gui/${PKGNAME} >${httpdconf}/${PKGNAME}.conf
                if ! grep ${PKGNAME} ${httpdconf}/httpd_package2.conf >/dev/null
                then
                        echo Include ${httpdconf}/${PKGNAME}.conf >>${httpdconf}/httpd_package2.conf
                fi
                touch /tmp/restart_httpd
        fi
    fi
}

Shutdown()
{
	echo "Stopping FFP"
	local envfile=/tmp/.ffpstick/helper.inc
	if [ -f ${envfile} ] ; then
		. ${envfile}
		local logroot=${ADMIN_DIR}/zy-pkgs/ffp
		mkdir -p $logroot
		exec >>$logroot/ffp.log 2>&1
		echo ${FFPROOT}/after_booting.sh StopFFP -t zypkg -r ${FFPROOT} -c "${CHROOTDIR}"
		${FFPROOT}/after_booting.sh StopFFP -t zypkg -r ${FFPROOT} -c "${CHROOTDIR}"
	fi
        
	local httpdconf=/etc/pkg_service_conf
        if [ -d ${httpdconf} ] ; then
                grep -v ${PKGNAME} ${httpdconf}/httpd_package2.conf >/tmp/$$.httpd.conf
                mv /tmp/$$.httpd.conf ${httpdconf}/httpd_package2.conf
                touch /tmp/restart_httpd
        fi
}

Disable()
{
    mkdir -p ${CONFIG_DIR}
    echo "Disabled" >${CONFIG_FILE}
    Shutdown 
# 2012-08-26:
# after_booting.sh should be disabled, else an FFP-stick could erroneously
# start the zypkg 
    chmod a-x ${FFPROOT}/after_booting.sh
}

Enable()
{
    mkdir -p ${CONFIG_DIR}
    echo "Enabled" >${CONFIG_FILE}
    chmod a+x ${FFPROOT}/after_booting.sh
    Startup 
}

[ -f /tmp/ffp.log ] && echo ` date ` $0 $@ >>/tmp/ffp.log

case $1 in
    getlink)
	GetLink
	;;
    status)
	Status
	;;
    startup)
	Startup 
	;;
    shutdown)
	Shutdown
	;;
    enable)
	Enable
	;;
    disable)
	Disable
	;;
    nastype)
	GetNasType
	;;
esac

exit 0

