#!/bin/bash
#
# Setup neutron for a new cloud.
#
# Assumes an OpenStack rc file has been sourced already to provide credentials
# and endpoint information.

set -eu
set -o pipefail

# Future work:
# Make this take options
# or perhaps eliminate it and describe it as raw commands in incubator.

# Start of DHCP range
ALLOCATION_START=$1
# End of DHCP range
ALLOCATION_END=$2
# Network CIDR
NETWORK_CIDR=$3
# Where to route traffic
NETWORK_GATEWAY=$4
# Where the metadata service is - ideally nova-bm would manage this:
# https://bugs.launchpad.net/tripleo/+bug/1239481
METADATA_SERVER=$5
# If non-empty create a provider flat network with this name otherwise create a
# virtual network and setup a router etc.
PHYSICAL_NETWORK=${6:-""}
# Start of floating range
FLOATING_START=${7:-""}
# End of floating range
FLOATING_END=${8:-""}
# Floating CIDR
FLOATING_CIDR=${9:-""}

# Create command line parameters
if [ -n "$ALLOCATION_START" -a -n "$ALLOCATION_END" ] ; then
    ALLOCATION_POOL="start=${ALLOCATION_START},end=${ALLOCATION_END}"
fi

# Find the admin tenant.
TENANT_ID=$(keystone tenant-list | grep ' admin ' | awk '{print $2}')

if [ -n "$PHYSICAL_NETWORK" ] ; then
    # Underclouds
    NET_NAME=$PHYSICAL_NETWORK
    NET_EXTRA="--tenant_id $TENANT_ID --provider:network_type flat --provider:physical_network $PHYSICAL_NETWORK"
    SUBNET_EXTRA="--tenant_id $TENANT_ID --host_routes type=dict list=true destination=169.254.169.254/32,nexthop=$METADATA_SERVER"
else
    # Overclouds
    NET_NAME="default-net"
    NET_EXTRA="--shared"
    SUBNET_EXTRA=""
fi

NET_ID=$(neutron net-create $NET_NAME $NET_EXTRA | grep ' id ' | awk '{print $4}')
SUBNET_ID=$(neutron subnet-create --ip_version 4 ${ALLOCATION_POOL:+--allocation-pool $ALLOCATION_POOL} ${NETWORK_GATEWAY:+--gateway $NETWORK_GATEWAY} $NET_ID $NETWORK_CIDR $SUBNET_EXTRA | grep ' id ' | awk '{print $4}')

if [ -z "$PHYSICAL_NETWORK" ] ; then
    neutron router-create default-router
    neutron router-interface-add default-router $SUBNET_ID
fi

if [ -n "$FLOATING_START" -a -n "$FLOATING_END" -a -n "$FLOATING_CIDR" ] ; then
    neutron net-create ext-net --router:external=True
    SUBNET_ID=$(neutron subnet-create ext-net $FLOATING_CIDR --disable-dhcp \
                --allocation-pool start=$FLOATING_START,end=$FLOATING_END)
    neutron router-gateway-set default-router ext-net
fi
