#!/bin/bash

set -eux

OK_FILE=/opt/stack/.undercloud-setup

if [ -f $OK_FILE ]; then
    exit
fi

source /root/tripleo-undercloud-passwords
source /root/stackrc

# Add scripts directory from tripleo-incubator to the path.
if [ ! -e /etc/profile.d/tripleo-incubator-scripts.sh ]; then
    echo export PATH=\$PATH:/opt/stack/tripleo-incubator/scripts/ >> \
        /etc/profile.d/tripleo-incubator-scripts.sh
fi

# Make sure we have the latest $PATH set.
source /etc/profile.d/tripleo-incubator-scripts.sh

if [ ! -f /root/.ssh/authorized_keys ]; then
    sudo mkdir -p /root/.ssh
    sudo chmod 7000 /root/.ssh/
    sudo touch /root/.ssh/authorized_keys
    sudo chmod 600 /root/.ssh/authorized_keys
fi

if [ ! -f /root/.ssh/id_rsa ]; then
    ssh-keygen -b 1024 -N '' -f /root/.ssh/id_rsa
fi

cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys

KEYSTONE_SERVICE=keystone
if [ -f /lib/systemd/system/openstack-keystone.service ]; then
    KEYSTONE_SERVICE=openstack-keystone
fi

# Ensure keystone is up before continuing on.
# Waits for up to 2 minutes.
tripleo wait_for 12 10 service $KEYSTONE_SERVICE status

# Because keystone just still isn't up yet...
sleep 20

export UNDERCLOUD_IP=$(os-apply-config --key local-ipv4 --type netaddress)

tripleo init-keystone -p $UNDERCLOUD_ADMIN_PASSWORD $UNDERCLOUD_ADMIN_TOKEN \
    $UNDERCLOUD_IP admin@example.com root@$UNDERCLOUD_IP

tripleo setup-endpoints \
    $UNDERCLOUD_IP \
    --glance-password $UNDERCLOUD_GLANCE_PASSWORD \
    --heat-password $UNDERCLOUD_HEAT_PASSWORD \
    --neutron-password $UNDERCLOUD_NEUTRON_PASSWORD \
    --nova-password $UNDERCLOUD_NOVA_PASSWORD

keystone role-create --name heat_stack_user

DHCP_START=$(os-apply-config --key neutron.dhcp_start --type netaddress)
DHCP_END=$(os-apply-config --key neutron.dhcp_end --type netaddress)
NETWORK_CIDR=$(os-apply-config --key neutron.network_cidr --type raw)
NETWORK_GATEWAY=$(os-apply-config --key neutron.network_gateway --type netaddress)
METADATA_SERVER=$UNDERCLOUD_IP
PHYSICAL_NETWORK=ctlplane

tripleo setup-neutron \
    $DHCP_START $DHCP_END \
    $NETWORK_CIDR $NETWORK_GATEWAY \
    $METADATA_SERVER $PHYSICAL_NETWORK

# Delete initial flavors
for flavor in m1.tiny m1.small m1.medium m1.large m1.xlarge; do
    if nova flavor-show "$flavor" &> /dev/null; then
        nova flavor-delete "$flavor"
    fi
done

touch $OK_FILE
