#!/bin/sh

################################################################################
#      Copyright (C) 2009-2010 OpenELEC.tv
#      http://www.openelec.tv
#
#  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.
#
#  You should have received a copy of the GNU General Public License
#  along with OpenELEC.tv; see the file COPYING.  If not, write to
#  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
#  http://www.gnu.org/copyleft/gpl.html
################################################################################

# start ssh server
#
# runlevels: openelec, textmode

. /etc/profile

RSA_KEY_FILE="/storage/.cache/dropbear/dropbear_rsa_host_key"
RSAPUB_KEY_FILE="/storage/.cache/dropbear/dropbear_rsa_host_key.pub"
DSS_KEY_FILE="/storage/.cache/dropbear/dropbear_dss_host_key"

(

  # Check for the Dropbear RSA key
    if [ ! -f $RSA_KEY_FILE ] ; then
      progress "SSH: generating rsa key"

      mkdir -p /storage/.cache/dropbear
        dropbearkey -t rsa -f $RSA_KEY_FILE > /dev/null 2>&1
    fi

  # Check for the Dropbear RSA public key
    if [ ! -f $RSAPUB_KEY_FILE ] ; then
      progress "SSH: generating rsa public key"

      mkdir -p /storage/.cache/dropbear
        dropbearkey -f $RSA_KEY_FILE -y > $RSAPUB_KEY_FILE
    fi

  # Check for the Dropbear DSS key
    if [ ! -f $DSS_KEY_FILE ] ; then
      progress "SSH: generating dsa key"

      mkdir -p /storage/.cache/dropbear
        dropbearkey -t dss -f $DSS_KEY_FILE > /dev/null 2>&1
    fi

  # Check for predifined known hosts file
    if [ -f /etc/ssh/known_hosts -a ! -f $HOME/.ssh/known_hosts ] ; then
      progress "SSH: setup predifined known hosts"

      mkdir -p /$HOME/.ssh
        cp /etc/ssh/known_hosts $HOME/.ssh
    fi

  progress "Starting SSH Server"

  $IONICE mkdir -p /var/log
  $IONICE touch /var/log/lastlog
  $IONICE touch /var/log/wtmp

  dropbear -b /etc/issue -P /var/run/dropbear.pid

)&
