#!/bin/bash

. /usr/local/lib/gce-funcs
. /root/test-config

logger -i "Entered nfs setup"

set -vx
filestore_info=$(mktemp)
if ! gcloud filestore instances describe "$FILESTORE_NAME" \
     --location="$FILESTORE_LOCATION" --format=json > "$filestore_info" ; then
    network=$(gcloud compute instances describe $instance --format=json | \
		  jq ".networkInterfaces[].network" | \
		  sed -e 's;^".*/;;' -e 's/"$//')
    gcloud filestore instances create "$FILESTORE_NAME" \
	   --file-share=capacity="$FILESTORE_SIZE",name=nfstest \
	   --tier="$FILESTORE_TIER" --network=name="$network" \
	   --location="$FILESTORE_LOCATION"
    if ! gcloud filestore instances describe "$FILESTORE_NAME" \
	 --location="$FILESTORE_LOCATION" --format=json > "$filestore_info" ; then
	logger -i "Couldn't start filestore"
	exit 1
    fi
fi
ipaddr=$(cat "$filestore_info" | jq '.networks[].ipAddresses[]' | \
	     sed -e 's/^"//' -e 's/"$//')
FILESTORE_TOP="$ipaddr:/nfstest"
FILESTORE_SUBDIR="$instance"
mount -t nfs "$FILESTORE_TOP" /mnt
mkdir -p /mnt/$FILESTORE_SUBDIR/test
mkdir -p /mnt/$FILESTORE_SUBDIR/scratch
touch /mnt/busy-$FILESTORE_SUBDIR
umount /mnt
echo FILESTORE_NAME=\"$FILESTORE_NAME\" > /run/filestore-param
echo FILESTORE_LOCATION=\"$FILESTORE_LOCATION\" >> /run/filestore-param
echo FILESTORE_TIER=\"$FILESTORE_TIER\" >> /run/filestore-param
echo FILESTORE_TOP=\"$FILESTORE_TOP\" >> /run/filestore-param
echo FILESTORE_SUBDIR=\"$instance\" >> /run/filestore-param
