#!/bin/bash

set -e

# If there is a /vagrant/Packages file, pull packages from there
# (assuming they have been built locally). Otherwise, use the default
# public repository.
default_repo="deb http://www.incal.net/ale/debian autoradio/"
local_repo="deb file:///vagrant ./"
if [ -e /vagrant/Packages ]; then
    echo "Using local package repository from /vagrant" >&2
    repo="${local_repo}"
else
    echo "Using default package repository" >&2
    repo="${default_repo}"
fi

# Install our Debian apt repository.
echo "${repo}" > /etc/apt/sources.list.d/autoradio.list

# Install the configuration.
DOMAIN="${DOMAIN:-$1}"
if [ -z "${DOMAIN}" ]; then
    echo "Must set \$DOMAIN" >&2
    exit 1
fi
cat >/etc/default/autoradio <<EOF
DOMAIN="--domain=${DOMAIN}"
EOF

cat >/etc/default/icecast2 <<EOF
CONFIGFILE="/etc/icecast2/icecast.xml"
USERID=icecast2
GROUPID=icecast
ENABLE=true
EOF

cat >/etc/default/etcd <<EOF
ETCD_LISTEN_PEER_URLS=http://0.0.0.0:2380
ETCD_INITIAL_ADVERTISE_PEER_URLS=http://$(hostname -s):2380
ETCD_LISTEN_CLIENT_URLS=http://0.0.0.0:2379
ETCD_ADVERTISE_CLIENT_URLS=http://$(hostname -s):2379
ETCD_INITIAL_CLUSTER_STATE=new
#ETCD_INITIAL_CLUSTER=node1=http://192.168.50.2:2380,node2=http://192.168.50.3:2380,node3=http://192.168.50.4:2380
ETCD_INITIAL_CLUSTER=node1=http://node1:2380,node2=http://node2:2380,node3=http://node3:2380
EOF

# Install the required packages.
export DEBIAN_FRONTEND=noninteractive
apt-get -qq update
yes n | apt-get install -y --force-yes -q etcd autoradio-server

echo "All done (?)" 1>&2
exit 0