#!/bin/bash
# Install pre-requisites that we depend on for maintenance and operation
# of the package
set -e
#
MYPROGNAME=`basename $0`
MYBUNDLE="ssh_certificate"
MYUSERNAME=${2:-ubuntu}

if ! [[ ( "$1" == "enable" || "$1" == "remove" ) ]]
then
    cat <<EOF

${MYBUNDLE} remote host configuration set up script.

In order for ${MYBUNDLE} to be able to update a few /etc/ssh/
configuration files to keep certificates, trusted CAs, and revoked
user configuration in line with the certificate database, it needs to
be able to invoke a few sudo commands from ubuntu without supplying a
password.  Running this script on a target server will permit ubuntu
to invoke this limited set of commands without password.

NOTE:  This script is fairly self contained. To enable on a
ubuntu host.  Upload the script to that host and invoke it 
there. 

Use: ${MYPROGNAME} enable [username]
       To install the rules we need.
       If you do not supply username it will default to ubuntu

     ${MYPROGNAME} remove 
       To remove the rules we previously installed.

     ${MYPROGNAME} 
       To display this information.
EOF
    exit 1
fi

if [[ "$1" == "enable" ]]
then
    echo enabling for ${MYUSERNAME}
    sudo tee /etc/sudoers.d/90-ssh-certificate-enabled <<EOF
# The ${MYBUNDLE} package needs these commands to be passwordless 
# under sudo for user ${MYUSERNAME} 
${MYUSERNAME} ALL=NOPASSWD:/bin/sed
${MYUSERNAME} ALL=NOPASSWD:/usr/bin/tee
EOF
    sudo chmod 0440 /etc/sudoers.d/90-ssh-certificate-enabled
    echo ${MYPROGNAME} feature enabled.
fi

if [[ "$1" == "remove" ]]
then
    sudo rm /etc/sudoers.d/90-ssh-certificate-enabled
    echo ${MYPROGNAME} feature removed.
fi

