#!/bin/bash

#
# Generate & transfer the necessary SSH keys across the OnApp system.
# Paul Morris - paul@onapp.com

DBCONF="/onapp/interface/config/database.yml"
MCONF="/onapp/interface/config/on_app.yml"
FTVAR="ssh_file_transfer_server"

KEYS="/tmp/onappkeys"
HVKEYS="/tmp/hvonappkeys"
TMPKEYS="/tmp/hvonappkeystmp"
BKKEY="/tmp/bkkey"

#Are we root
if [ `whoami` != "root" ]; then
    echo "Error: You must be root to run this script"
    exit 1;
fi

if [ ! -f ${DBCONF} ]; then
    echo "Error: You don't seem to have a valid database configuration file, exiting."
    exit 1;
fi

SQLHOSTNAME=`grep host ${DBCONF} | awk '{print $2}' | head -n 1`
SQLUSERNAME=`grep username ${DBCONF} | awk '{print $2}' | head -n 1`
SQLPASSWORD=`grep password ${DBCONF} | awk '{print $2}' | head -n 1`
BACKUPIP=`grep ${FTVAR} ${MCONF} | awk '{print $2}'`

if ! mysql -h ${SQLHOSTNAME} -u ${SQLUSERNAME} -p"${SQLPASSWORD}" onapp -Bse "exit" &>/dev/null; then
    echo -ne "Error: Failed to connect to MySQL database\n Please enter your database password:"
    read SQLPASSWORD
    if ! mysql -h ${SQLHOSTNAME} -u ${SQLUSERNAME} -p"${SQLPASSWORD}" onapp -Bse "exit" &>/dev/null; then
        echo "Error: Failed to connect to MySQL database"
        exit 1;
    fi
fi

HYPERVISORS=`mysql -h ${SQLHOSTNAME} -u ${SQLUSERNAME} -p"${SQLPASSWORD}" onapp -Bse "SELECT ip_address FROM hypervisors ORDER BY label"`
BKSERVERS=`mysql -h ${SQLHOSTNAME} -u ${SQLUSERNAME} -p"${SQLPASSWORD}" onapp -Bse "SELECT ip_address FROM backup_servers"`
HVCOUNT=`mysql -h ${SQLHOSTNAME} -u ${SQLUSERNAME} -p"${SQLPASSWORD}" onapp -Bse "SELECT count(*) FROM hypervisors"`
BKCOUNT=`mysql -h ${SQLHOSTNAME} -u ${SQLUSERNAME} -p"${SQLPASSWORD}" onapp -Bse "SELECT count(*) FROM backup_servers"`

# Continue if we have HVs to process
if [ ${HVCOUNT} -le 0 ]; then
    echo "Error: No Hypervisors added to cloud"
    exit 1;
else
    echo " - Hypervisors detected, continuing with key installation..."
fi

# Generate the keys on the CP
echo " - Generating the keys for the CP server (users root & onapp)..."
if [ ! -f /root/.ssh/id_rsa.pub ]; then
    rm /root/.ssh/id_rsa.pub &>/dev/null
    rm /root/.ssh/id_rsa &>/dev/null
    ssh-keygen -b 4096 -t rsa -q -f /root/.ssh/id_rsa -N "" &>/dev/null
fi

if [ ! -f /home/onapp/.ssh/id_rsa.pub ]; then
    rm /home/onapp/.ssh/id_rsa.pub &>/dev/null
    rm /home/onapp/.ssh/id_rsa &>/dev/null
    ssh-keygen -b 4096 -t rsa -q -f /home/onapp/.ssh/id_rsa -N "" &>/dev/null
    chown -R onapp:onapp /home/onapp/.ssh &>/dev/null
fi

# Check for backup servers
if [ ${BKCOUNT} -le 0 ]; then
    if [ ${BACKUPIP} == "127.0.0.1" ]; then
        echo -ne "Please configure your backup servers IP address first \n \
	          Settings --> Configuration --> Backups/Templates \n \
	          Enable: \"Use SSH file transfer\" \n \
	          Enter the IP address of your backup server. \n"
        exit 1;
    fi
else
    #Loop through BSs and add the necessary keys
    echo " - Processing ${BKCOUNT} backup server(s)..."
    for i in ${BKSERVERS}; do
        echo " -- Processing ${i}"

        #Generate a private key file on the backup server if necessary
	echo " - Generating a key pair on the file transfer server..."
	echo " -- !!! Enter the file transfer servers password... !!!"
	ssh -o StrictHostKeyChecking=no root@${i} \
	 "if [ ! -e /root/.ssh/id_rsa ]; then ssh-keygen -b 4096 -t rsa -q -f /root/.ssh/id_rsa -N \"\"; fi;" &>/dev/null

	# Put the CP keys on the backup server
        echo " -- Adding the control panel keys to backup server ${i}"
        echo " --- !!! Enter the root password for backup server: ${i}... !!!"
        scp -o StrictHostKeyChecking=no /home/onapp/.ssh/id_rsa.pub root@${i}:/root/.ssh/authorized_keys && sleep 3 &> /dev/null

     # Add the entry to known hosts automatically
     echo " -- Adding the backup server key to known hosts on control panel"
     sudo -u onapp ssh -o StrictHostKeyChecking=no -l root ${i} exit &>/dev/null
    done
fi

# Generate the keys on the file transfer server if necessary (usually only if backup server is separate from controller - old scheme)
echo " - Generating a key pair on the file transfer server..."
echo " -- !!! Enter the file transfer servers password... !!!"
ssh -o StrictHostKeyChecking=no root@${BACKUPIP} \
 "if [ ! -e /root/.ssh/id_rsa ]; then ssh-keygen -b 4096 -t rsa -q -f /root/.ssh/id_rsa -N \"\"; fi;" &>/dev/null

# Take a copy of the file transfer servers public key
echo " - Taking a copy of the file transfer servers public key"
echo " -- !!! Enter the file transfer servers password... !!!"
scp -o StrictHostKeyChecking=no root@${BACKUPIP}:/root/.ssh/id_rsa.pub ${BKKEY} &> /dev/null

# Create a combined keyfile for later
echo " - Creating combined keyfile of CP server keys..."

# Create keys file
if ! touch ${KEYS}; then
    echo "Error: Failed to create ${KEYS} file"
    exit 1;
fi

cat /home/onapp/.ssh/id_rsa.pub >> ${KEYS}
cat /root/.ssh/id_rsa.pub >> ${KEYS}
cat ${BKKEY} >> ${KEYS}

if ! touch ${TMPKEYS}; then
    echo "Error: Failed to create ${TMPKEYS} file"
    exit 1;
fi

if ! touch ${HVKEYS}; then
    echo "Error: Failed to create ${HVKEYS} file"
    exit 1;
fi

#Loop through HVs and add the necessary keys
echo " - Processing hypervisors..."
for i in ${HYPERVISORS}; do
     echo " -- Processing ${i}"
     #Copy over the keys

     # Generate the keys on the hypervisor, we do this first to make sure the ~/.ssh dir exists
     echo " -- Generating keys on hypervisor ${i}"
     echo " --- !!! Enter the root password for Hypervisor: ${i}... !!!"
     ssh -o StrictHostKeyChecking=no root@${i} \
      "if [ -e /root/.ssh/id_rsa ]; then rm /root/.ssh/id_rsa; fi; \
       if [ -e /root/.ssh/id_rsa.pub ]; then rm /root/.ssh/id_rsa.pub; fi; \
       ssh-keygen -b 4096 -t rsa -q -f /root/.ssh/id_rsa -N \"\""

     # Put the keys onto the HV
     echo " -- Adding the control panel keys to hypervisor ${i}"
     echo " --- !!! Enter the root password for Hypervisor: ${i}... !!!"
     scp -o StrictHostKeyChecking=no ${KEYS} root@${i}:/root/.ssh/authorized_keys &> /dev/null
     # Wait a few second to avoid timing issue with connection below
     sleep 5

     # Copy the hypervisor public key and append a tmp file
     echo " -- Copying the hypervisor keys to a tmp file for later..."
     scp root@${i}:/root/.ssh/id_rsa.pub ${TMPKEYS} &>/dev/null
     cat ${TMPKEYS} >> ${HVKEYS}

     # Add the entry to known hosts automatically
     echo " -- Adding the hypervisor key to known hosts on control panel"
     sudo -u onapp ssh -o StrictHostKeyChecking=no -l root ${i} exit &>/dev/null
done

echo " - Processing the backup server..."
# Combine all key for backup server and copy over.
cat ${HVKEYS} >> ${KEYS}

# Transfer the control panel keys to the backup server
echo " - Transferring the control panel keys to the backup server..."
echo " -- !!! Enter the backup servers password... !!!"
scp -o StrictHostKeyChecking=no ${KEYS} root@${BACKUPIP}:/root/.ssh/authorized_keys &> /dev/null
#Aviod timing issue with connections below
sleep 5

# Add the entry to known hosts automatically for control panel
echo " - Adding the backup server to control panel known hosts file..."
sudo -u onapp ssh -o StrictHostKeyChecking=no -l root ${BACKUPIP} exit &>/dev/null
ssh -o StrictHostKeyChecking=no -l root ${BACKUPIP} exit &>/dev/null

# Add the entry to know hosts automatically for hypervisors
for i in ${HYPERVISORS}; do
    echo " - Adding backup server keys to hypervisor ${i}"
    sudo -u onapp ssh -o StrictHostKeyChecking=no -l root ${i} ssh -o StrictHostKeyChecking=no -l root ${BACKUPIP} exit &>/dev/null
    sleep 2
done

# Tidy up various files
echo " - Tidying up after installations"
rm ${HVKEYS} &>/dev/null
rm ${TMPKEYS} &>/dev/null
rm ${KEYS} &>/dev/null
rm ${BKKEY} &> /dev/null

# Installation completed
echo -e " - Installation completed\n"
