#!/bin/bash
# Copyright 2013 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; version 2.1.
#
# 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author: Juhapekka Piiroinen <juhapekka.piiroinen@canonical.com>

. `dirname $0`/functions.inc

USERNAME=$2

function check_key {
	echo "Checking for keys.."
	KEY=`cat $SSHIDENTITY.pub`
	set +e
	PHABLET_KEYS=`adb_shell "cat /home/$USERNAME/.ssh/authorized_keys2"`
	KEYS=`echo $PHABLET_KEYS | grep "$KEY"`
	set -e
	echo
	echo "Host key is:"
	echo $KEY
	echo
	echo "We have following keys on the device: "
	echo $KEYS
	if [[ -z $KEYS || $KEYS == *No\ such* ]]; then
		echo "*no keys*"
		echo
		deploy_key
	else
		echo
		echo "The host key has been already deployed."
	fi
}

function deploy_key {
	echo "Deploy the host key to the device.."
	KEY=`cat $SSHIDENTITY.pub`
	phablet_shell "mkdir -p /home/$USERNAME/.ssh"
	echo "..key folder created"
	phablet_shell "echo $KEY >> /home/$USERNAME/.ssh/authorized_keys2"
	echo "..key deployed!"
}

function generate_key {
	echo "Generating host key.."
	ssh-keygen -t rsa -N '' -f $SSHIDENTITY -b 768
}

#################

if [[ -f $SSHIDENTITY ]]; then
  check_key
else
  generate_key
  deploy_key
fi
