###############
# build tools #
###############

set -x

chown -R vagrant:vagrant ~vagrant/.ssh

apt-get update
apt-get install -y manta

##################
# Install GO
##################
GO_VERSION="1.5.1"
GO_SHASUM="5817fa4b2252afdb02e11e8b9dc1d9173ef3bd5a"
wget -nv https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz
echo "${GO_SHASUM}  go${GO_VERSION}.linux-amd64.tar.gz" | sha1sum --check
tar -C /usr/local -xzf go${GO_VERSION}.linux-amd64.tar.gz

echo '
export GOPATH="/go"
export PATH="/usr/local/go/bin:/go/bin/:$PATH"
export ENVIRONMENT=staging
export APP=mekansm
' >> /home/vagrant/.profile

source /home/vagrant/.profile

apt-get -y install git

##################
# Setup Database #
##################
POSTGRES_VERSION="9.1"
apt-get install -y postgresql-${POSTGRES_VERSION} postgresql-server-dev-all

# Goose is used for postgres
go get bitbucket.org/liamstask/goose/cmd/goose
go install bitbucket.org/liamstask/goose/cmd/goose
sudo -u vagrant -i go get bitbucket.org/liamstask/goose/cmd/goose
sudo -u vagrant -i go install bitbucket.org/liamstask/goose/cmd/goose
# Create user:
sudo -u postgres /usr/lib/postgresql/${POSTGRES_VERSION}/bin/createuser vagrant -s
# Create database:
sudo -u postgres /usr/lib/postgresql/${POSTGRES_VERSION}/bin/createdb vagrant -E utf8

# Fix permissions
sed -i 's!host\s\+all\s\+all\s\+127.0.0.1/32\s\+md5!host all all 127.0.0.1/32 trust!' /etc/postgresql/${POSTGRES_VERSION}/main/pg_hba.conf
/etc/init.d/postgresql reload

# Updating database schema with goose
cd /usr/src/mekansm
goose up


####################################3
# Installing and Running mekansm
####################################3
cd /usr/src/mekansm
apt-get install -y python python-dev
apt-get install -y python-setuptools # necessary on ubuntu 12.04
easy_install pip # necessary on ubuntu 12.04
pip install -e .
python ./setup.py install

PORT=8080
# sample yaml_config
cat << EOF > /tmp/yaml_config
aws:
  #-
    #profile: default
    #region: us-east-1
  -
    profile: twitch-core-services
    region: us-west-2
database:
    host: 127.0.0.1
    port: 5432
    user: picong
    password: 
    database: picong
    engine:
        echo: true
        echo_pool: true
        strategy: threadlocal
        max_overflow: 40
threadpool:
    frequency: 2
    max: 40
    maxspare: 40
    min: 20
    minspare: 10
    shrink_frequency: 10
    log_frequency: 3
EOF


python -m mekansm ${PORT} /tmp/yaml_config

