set -e
# make sure directory $1 doesn't exist
if [[ -d $1 ]]; then
    echo "Directory $1 exits already. Use a different name"
    exit 1
fi
# make sure database $1 doesn't exist
if sudo -i -u postgres psql -lqt | cut -d \| -f 1 | grep -qw $1; then
    echo "Database $1 exits already. Use a different name"
    exit 1
fi
VENV=venv
virtualenv $VENV
$VENV/bin/pip install "Django>=1.8,<1.9"
DB_USER=$1
DB_PASS=$1
DB_NAME=$1
sudo -i -u postgres psql -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS';"
sudo -i -u postgres psql -c "CREATE DATABASE $DB_NAME WITH OWNER $DB_USER;"
sudo -i -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;"
sudo -i -u postgres psql -d $DB_NAME -c "CREATE EXTENSION postgis;"
sudo -i -u postgres psql -d $DB_NAME -c "CREATE EXTENSION postgis_topology;"
sudo -i -u postgres psql -d $DB_NAME -c "CREATE EXTENSION fuzzystrmatch;"
sudo -i -u postgres psql -d $DB_NAME -c "CREATE EXTENSION postgis_tiger_geocoder;"
$VENV/bin/django-admin.py startproject --template=https://github.com/tendenci/tendenci-project-template/archive/master.zip $1
cd $1
../$VENV/bin/pip install -r requirements/dev.txt
curl https://gist.githubusercontent.com/jennyq/45de71a93cff774c593d/raw/30ede14eb133de66cc839cc0458a1e915368534e/setup_keys.sh | bash
sed -i "s/<DB_NAME>/$1/g" conf/local_settings.py
sed -i "s/<DB_USER>/$1/g" conf/local_settings.py
sed -i "s/<DB_PASS>/$1/g" conf/local_settings.py
../$VENV/bin/python manage.py migrate --noinput
../$VENV/bin/python manage.py collectstatic --noinput
../$VENV/bin/python manage.py update_settings
../$VENV/bin/python manage.py clear_theme_cache
../$VENV/bin/python manage.py populate_default_entity
../$VENV/bin/python manage.py populate_entity_and_auth_group_columns
chmod -R -x+X media
../$VENV/bin/python manage.py createsuperuser --noinput --username=admin --email=admin@example.com
echo "from django.contrib.auth.models import User; superuser = User.objects.get(username='admin'); superuser.set_password('admin'); superuser.save()" | ../$VENV/bin/python manage.py shell
../$VENV/bin/python manage.py runserver