#!/bin/sh

set -e

# Usage: devel-system-setup $STAGING_FILLER_NAME

FILLER_NAME="$1"

if [ -z "$FILLER_NAME" ]; then
	echo "A staging-filler must be specified"
	echo "Usage: $0 FILLER_NAME"
	exit 1
fi

#Set up the initial /src disk
if [ -e /dev/disk/by-label/src ]
then
	echo "Disk labelled src found"
else
	echo "Disk labelled src not found. Initializing /dev/sdb as src"
	mkfs.btrfs -L src /dev/sdb
fi

#Ensure the /src directory exists
mkdir -p /src

#Add the /src disk to /etc/fstab if it doesn't exist
grep "LABEL=src" /etc/fstab >/dev/null || echo 'LABEL=src /src btrfs defaults 0 2' >>/etc/fstab

#Mount the disk so that it can be configured
mount -a 

#Retrieve the staging-filler
if ! [ -e /src/staging-filler ]; then
	mkdir /src/staging-filler
fi

if ! [ -e "/src/staging-filler/$FILLER_NAME.tar.gz" ]; then
	echo "Downloading staging-filler: $FILLER_NAME"
	wget -P /src/staging-filler "http://download.baserock.org/baserock/$FILLER_NAME.tar.gz"
fi


#Ensure the cache and temp directories exist
mkdir -p /src/cache
mkdir -p /src/tmp

#Create morph.conf
cat >/src/morph.conf <<EOF
[config]
log = /src/morph.log
cachedir = /src/cache
tempdir = /src/tmp
staging-chroot = true
staging-filler = /src/staging-filler/$FILLER_NAME.tar.gz
trove-host = trove.baserock.org
trove-prefix = ct
EOF

#Ensure morph uses our morph.conf
[ -e $HOME/.morph.conf ] && rm $HOME/.morph.conf
ln -s /src/morph.conf $HOME/.morph.conf

echo "Initial setup complete."
