#!/bin/bash
# this is our pre-network processing entry-point
#
# chkconfig: 3 20 80
# description: networking helper
# author: saaswatch@vmware.com
# version: 2.1.2.RELEASE
# build date:
#
### BEGIN INIT INFO
# Provides: hzn-network
# Required-Start: random
# Required-Stop:
# X-Start-Before: network
# Default-Start:  3
# Default-Stop:   0
# Description:    horizon network setup
### END INIT INFO

if [ "$1" != "start" ] ; then
    # only do something on start
    exit 0
fi

. /usr/local/horizon/scripts/flag.inc

function generateSshHostKey(){

    if [ ! -f $FLAG_FIRSTBOOT ]; then
        echo Removing all existing SSH Host keys
        rm -f /etc/ssh/ssh_host*_key /etc/ssh/ssh_host*_key.pub
    fi

    RSA_HOSTKEY=$(grep -E "^HostKey .*rsa" /etc/ssh/sshd_config | awk '{print $2}')
    if [ -n "${RSA_HOSTKEY}" -a ! -e ${RSA_HOSTKEY} ]; then
      echo Generating sshd hostkey ...
      ssh-keygen -f ${RSA_HOSTKEY} -N '' -t rsa -b 2048
      ssh-keygen -y -f $RSA_HOSTKEY > $RSA_HOSTKEY.pub
      chmod 600 $RSA_HOSTKEY
      chmod 644 $RSA_HOSTKEY.pub

      #prevent vaos from removing the key we just created.
      #This will also prevent the creation of the root ssh key, but that is taken
      #care of in the firstboot script.
      rm -f /opt/vmware/etc/vami/flags/vami_createsshkeys
    fi
}

if [ -f $FLAG_OWNSSHD ] ; then
    generateSshHostKey
fi

# configure networking and clone work, later stuff goes in hzn-sysconfig
if [ -f $FLAG_OWNVA ] ; then
  /usr/local/horizon/scripts/networkwizard.hzn onboot
fi
