#!/bin/bash

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

logger -i "Entered kcs cache scratch"

set -vx
KCS_DSK=kcs-cache-disk
CREATED_KCS_DEV=/dev/disk/by-id/google-kcs-cache
KCS_SIZE=60

d="$(gcloud compute --project $GCE_PROJECT disks list --filter="name = $KCS_DSK")"
if test -z "$d"
then
    logger -s "Create kcs cache PD"

    gcloud compute -q disks create "$KCS_DSK" \
    --size "${KCS_SIZE:-60}" \
    --zone "$ZONE" --type "${KCS_TYPE:-pd-balanced}"
fi

# attach the disk & turn off auto-delete
gcloud compute -q instances attach-disk ${instance} \
--disk "$KCS_DSK" --device-name kcs-cache --zone "$ZONE"
gcloud compute -q instances set-disk-auto-delete ${instance} \
--disk "$KCS_DSK" --no-auto-delete --zone "$ZONE" &

if ! test -e $CREATED_KCS_DEV
then
    logger -s "Couldn't create or attach the cache disk!"
    exit 1
fi

if test -z "$d"
then
    mkfs.ext4 $CREATED_KCS_DEV
fi

mkdir -p /cache
mount $CREATED_KCS_DEV /cache

mkdir -p /cache/ccache
echo export CCACHE_DIR=/cache/ccache >> /root/.bashrc

wait
exit 0
