#!/bin/sh
#
# -*- coding: iso-latin-1-unix; -*-

set -e
set -u


export PATH=/bin:/sbin:/usr/bin:/usr/sbin

user=root
keyurl=https://flussonic.com/public/flussonic_support_rsa.pub


if [ -f /etc/debian_version ]; then
    distro=debian
elif [ -f /etc/redhat-release ]; then
    distro=redhat
else
    echo Unknown distro
    exit 1
fi

echo Distro: $distro


if [ `id -u` != 0 ]; then
    echo Must run as root
    exit 1
fi


install_package()
{
    case $distro in
        debian)
            apt-get -y install $1
            ;;
        redhat)
            yum -y install $1
            ;;
    esac
}


if [ ! -x /usr/bin/wget ]; then
    install_package wget
fi


eval sshdir=~$user/.ssh
authfile=$sshdir/authorized_keys

#echo $sshdir

if [ ! -d $sshdir ]; then
    mkdir -p $sshdir
    #echo DEBUG $sshdir created
fi

chown $user $sshdir
chmod 700 $sshdir

if [ ! -f $authfile ]; then
    touch $authfile
fi

keyfile=/tmp/flussonic.pub
rm -f $keyfile
curl -s $keyurl -o $keyfile || { echo Cannot download key from $keyurl; exit 1; }

if ! grep -q -f $keyfile $authfile; then
    # echo DEBUG key not found
    cat $keyfile $authfile > $authfile.new
    mv -f $authfile.new $authfile
    echo ssh key added
fi

rm -f $keyfile

chown $user $authfile
chmod 600 $authfile
