#!/bin/sh
# ============================================================================
#
# This file is part of the 'Dropbear' package
# 
# 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>
#
# ============================================================================
PKG_NAME="Dropbear"
THIS_SCRIPT="Dropbear"
PKG_FIRMWARE=4

############################################################
## Check if we are in upgradig mode. From the point of view of the package
## an upgrade is a uninstall followed by a install. So if you want to preserve
## something over an upgrade, you have to detect it somehow
##
## Function sets PKG_UPGRADE > 0 when upgrading, 
## and PKG_UPGRADE=0 when not
############################################################
IsUpgrading()
{
	PKG_UPGRADING=0
	local dir=
	for dir in "/usr/local/zy-pkgs/" "/i-data/.system/zy-pkgs/"
	do
		local logfile=${dir}tmp/zypkg.log
		[ ! -f ${logfile} ] && continue

		local lastupdate=` grep "Upgrade Mode" ${logfile} | tail -n 1 | grep "\[${PKG_NAME}\]" | awk -v OFS=' ' '{print $1, $2}' `

	        [ "${lastupdate}" = "" ] && return 1

		local since1970=` TZ=GMT date -d "${lastupdate}" +%s `
		local now=`date +%s `
		local ago=""
		let ago=now-since1970
		[ $ago -eq 0 ] && ago=1
		[ 300 -gt $ago ] && PKG_UPGRADING=$ago && return 0

		return 1
	done

	# We shouldn't be here
	return 1
}

#############################################################
## Dummy logcode
#############################################################
Log() 
{
	return
}

######################################
## 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()
{
	return
}

######################################
## Status get and set
FrameworkStatus()
{
	local pkg_config_file="${PKG_ROOT}/config/${PKG_NAME}/config"
	if [ "get" = "$1" ] ; then
		if [ ! -f ${pkg_config_file} ] ; then
			FrameworkStatus set Disabled
		fi
		cat ${pkg_config_file}
		return
	elif [ "set" = "$1" ] ; then
		mkdir -p ` dirname ${pkg_config_file} `
		
		echo $2 >${pkg_config_file}
	fi
}

################################################
## Run or stop the package
FrameworkRun()
{
	if [ $1 -eq 1 ] ; then
		# Startup
		STATUS=` FrameworkStatus get `
		[ "$STATUS" != "Enabled" ] && return	# We're not enabled

		Startup
		return
	fi

	Shutdown
	
}

FrameworkVersion()
{
	local controlfile=${PKG_ROOT}/zypkg_conf/info/${PKG_NAME}.control
	local version=$( grep "^Version:" ${controlfile} | awk -F"zypkg" '{print $2}' )
	exit $version
}

FrameworkParseParams()
{
	case $1 in
		getlink)
			FrameworkGetLink
			;;
		status)
			FrameworkStatus get
			;;
		enable)
			FrameworkStatus set Enabled 
			FrameworkRun 1 </dev/null
			;;
		disable)
			FrameworkRun 0 </dev/null
			FrameworkStatus set Disabled 
			;;
		startup)
			FrameworkRun 1 </dev/null
			;;
		shutdown)
			FrameworkRun 0 </dev/null
			;;
		version)
			FrameworkVersion
			;;
	esac
}

Log

PKG_ROOT="/usr/local/zy-pkgs"


Startup()
{
# Dropbear server v2026.94 https://matt.ucc.asn.au/dropbear/dropbear.html
# Usage: dropbear [options]
# -b bannerfile   Display the contents of bannerfile before user login
#                 (default: none)
# -r keyfile      Specify hostkeys (repeatable)
#                 defaults: 
#                 - rsa /etc/dropbear/dropbear_rsa_host_key
#                 - ecdsa /etc/dropbear/dropbear_ecdsa_host_key
#                 - ed25519 /etc/dropbear/dropbear_ed25519_host_key
# -D              Directory containing authorized_keys file
# -R              Create hostkeys as required
# -F              Don't fork into background
# -e              Pass on server process environment to child process
# -E              Log to stderr rather than syslog
# -m              Don't display the motd on login
# -w              Disallow root logins
# -G              Restrict logins to members of specified group
# -s              Disable password logins
# -g              Disable password logins for root
# -B              Allow blank password logins
# -t              Enable two-factor authentication (both password and public key required)
# -T              Maximum authentication tries (default 10)
# -j              Disable local port/stream forwarding
# -k              Disable remote port/stream forwarding
# -a              Allow connections to forwarded ports from any host
# -c command      Force executed command
# -p [address:]port
#                 Listen on specified tcp port (and optionally address),
#                 up to 10 can be specified
#                 (default port is 22 if none specified)
# -P PidFile      Create pid file PidFile
#                 (default /var/run/dropbear.pid)
# -l <interface>
#                 interface to bind on
# -i              Start for inetd
# -W <receive_window_buffer> (default 24576, larger may be faster, max 10MB)
# -K <keepalive>  (0 is never, default 0, in seconds)
# -I <idle_timeout>  (0 is never, default 0, in seconds)
# -M <max_duration>  (0 is off, default 0, in seconds)
# -z    disable QoS
# -Q    <algo>   Print supported algorithms, or -Q help
# -V    Version
#

    local keyroot=${PKG_ROOT}/etc/dropbear/
    mkdir -p ${keyroot}
    [ -L /etc/dropbear ] && rm /etc/dropbear
    ln -s ${keyroot} /etc/dropbear

    local dropbear=${PKG_ROOT}/bin/dropbearmulti-2026.94.armv5 
			        
    for shell in /bin/sh /bin/bash /ffp/bin/sh /ffp/bin/bash
    do
	if ! grep ^${shell} /etc/shells >/dev/null 2>&1
        then
		echo ${shell} >>/etc/shells
        fi
    done
			
    for file in dbclient dropbearkey dropbearconvert ssh ssh-keygen
    do
	[ -L /bin/${file} ] && rm /bin/${file}
	ln -s ${dropbear} /bin/${file}
    done
    
    local sftpserver=$(which sftp-server)
    
    # If an sftpserver is available, put it in /lib/exec/, where this instance of dropbear uses it
    if [ "X${sftpserver}" != "X" ] 
    then
	    mkdir -p /lib/exec
	    [ -L /lib/exec/sftp-server ] && rm /lib/exec/sftp-server
	    ln -s ${sftpserver} /lib/exec/sftp-server
    fi
    
    ${dropbear} dropbear -R -a -P /var/run/dropbear.pid 
    return 0
}

Shutdown()
{
    [ -f /var/run/dropbear.pid ] && kill -9 $(cat /var/run/dropbear.pid)
    return 0
}



FrameworkParseParams "$@"

exit 0
