#!/bin/bash
set -e

N=200
NW1="mzmr_attach_and_start_vlan4000"
SUBNET1="${NW1}_subnet_1"
NW2="mzmr_attach_and_start_vlan4002"
SUBNET2="${NW2}_subnet_1"

source ~/overcloudrc.admin

for i in $(seq 1 $N); do
    IDX=$(printf "%03d" $i)

    NAME="mzmr_attach_and_start_${IDX}"
    PORT1="${NW1}_port_${IDX}"
    IP1="10.40.0.${i}"
    PORT2="${NW2}_port_${IDX}"
    IP2="10.40.2.${i}"

    echo "===== [$i/100] Create VM: $NAME ====="

    # Create server
    openstack server create \
        --flavor 2vcpu_8192bmem_ovs_flavor \
        --volume "$NAME" \
        --port "$PORT1" \
        --availability-zone az_1 \
        "$NAME"

    # Wait until server becomes ACTIVE
    while true; do
        STATUS=$(openstack server show "$NAME" -f value -c status)
        if [[ "$STATUS" == "ACTIVE" ]]; then
            echo "[$NAME] Server is ACTIVE."
            break
        fi
        echo "[$NAME] Waiting for server... (status=$STATUS)"
        sleep 5
    done

    # Stop server
    openstack server stop "$NAME"

    # Wait until server becomes SHUTOFF
    while true; do
        STATUS=$(openstack server show "$NAME" -f value -c status)
        if [[ "$STATUS" == "SHUTOFF" ]]; then
            echo "[$NAME] Server is SHUTOFF."
            break
        fi
        echo "[$NAME] Waiting for server to stop... (status=$STATUS)"
        sleep 5
    done

    # Attach second port
    openstack server add port "$NAME" "$PORT2"

    # Wait until the port is attached
    while true; do
        if openstack server show "$NAME" -f value -c addresses | grep -q "$IP2"; then
            echo "[$NAME] Port $PORT1 (IP=$IP2) attached."
            break
        fi
        echo "[$NAME] Waiting for port attach..."
        sleep 5
    done

    # Start server
    openstack server start "$NAME"
done