#!/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>
set -e 

KEYPATH=~/.ssh/ubuntudevice_id_rsa
USERNAME=$1
SHELL="adb shell chroot /data/ubuntu /usr/bin/env -i PATH=/bin:/usr/bin:/sbin:/usr/sbin:/tools/bin"

function check_key {

KEY=`cat $KEYPATH.pub`
KEYS=`$SHELL su -c "cat ~/.ssh/authorized_keys2 | grep '$KEY'" $USERNAME`
if [[ -z $KEYS || $KEYS == *No\ such* ]]; then
  echo "Deploying key.."
  deploy_key
else
  echo "Key has been already deployed"
fi
}

function deploy_key {
 KEY=`cat $KEYPATH.pub`
$SHELL su -c "mkdir -p ~/.ssh" $USERNAME
$SHELL su -c "echo $KEY >> ~/.ssh/authorized_keys2" $USERNAME
}

function generate_key {
ssh-keygen -t rsa -N '' -f $KEYPATH -b 768
}

#################
adb root &> /dev/null
adb wait-for-device > /dev/null

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