#!/bin/bash

DFLT="/etc/default/bit-awx"
if [ ! -e ${DFLT} -o ! -r ${DFLT} ]; then
    echo "Could not read ${DFLT}! Bailing."
    exit 255
fi
. ${DFLT}


uid=$(/usr/bin/getent passwd bit-awx)
if [ -z "$uid" ]; then
    echo "No 'bit-awx' user was found on this system. This user will be created now."
    echo 'bit-awx:x:0:0:root:/var/lib/bit-awx:/bin/bash' >> /etc/passwd
    pwconv
    mkdir -p /var/lib/bit-awx/.ssh/
    chown -R root:root /var/lib/bit-awx
    chmod -R 700 /var/lib/bit-awx/
else 
    echo "The 'bit-awx' user was found on this system."
fi


echo "Updating user 'bit-awx' authorized_keys."

tmpf=$(/bin/mktemp)
echo -n "from=\"" >> $tmpf

for elem in $(seq 0 2 $((${#bitips[@]} - 1)))
do
    b_host=${bitips[$elem]}
    b_ip=${bitips[$elem + 1]}
    echo "Adding host $b_host [$b_ip]"
    # Add IPv4 IPs as their IPv4-mapped-IPv6 addresses too
    # if echo "${b_ip}" | grep -qi "\."; then b_ip="$b_ip,::ffff:$b_ip"; fi
    echo -n "$b_ip " >> $tmpf
done

( cat $tmpf | sed -e 's/\s*$/"/' -e 's/ /,/g' ; echo " $sshpubkey" ) > ~bit-awx/.ssh/authorized_keys
rm -f $tmpf

chown root:root ~bit-awx/.ssh/authorized_keys
chmod 600 ~bit-awx/.ssh/authorized_keys

echo ""
echo "Done:"
ls -la ~bit-awx/.ssh/authorized_keys

echo ""
