#!/bin/bash

if [ "$1" == "--post-start" ]; then
	set -e

	PIDF="zdtm/static/cr_veth.pid.inprogress"
	while [ ! -f "$PIDF" ]; do
		sleep ".1"
	done

	TPID=$(cat $PIDF)
	ps xaf
	echo "-> $TPID"

	set -x

	ip l l
	ip link add zdtmvthc0 type veth peer name zdtmvthh0
	ip link set zdtmvthc0 netns $TPID

	ip link del zdtmbr0 || true # Ignore the failure
	ip link add zdtmbr0 type bridge
	ip link set zdtmbr0 up
	ip link set zdtmvthh0 master zdtmbr0
elif [ "$1" == "--post-restore" ]; then
	ip link list zdtmvthh0

	if ! ip link list zdtmvthh0 | fgrep -q 'master zdtmbr0'; then
		echo "Device missing or not in bridge"
		exit 1
	fi

	echo "Device OK"
elif [ "$1" == "--pre-restore" -o "$1" == "--clean" ]; then
	# Wait for the link to die
	ip l l
	while ip l l zdtmvthh0 ; do
		sleep ".5"
	done
fi
