#!/bin/bash

# Install pm2
echo "Installing pm2 globally via npm"
npm install -g --production pm2 > /dev/null

# Install dependencies
echo "Installing node dependencies via npm"
cd /opt/dstore && npm install --production > /dev/null

# Create user
echo "Creating PostgreSQL user"
echo "Enter username for PostgreSQL user: "
read pu
read -s -p "Enter password for user $pu: " pp
sed -i "s/POSTGRESQL_USER=dstore/POSTGRESQL_USER=$pu/g" /etc/dstore/dstore.conf
sed -i "s/POSTGRESQL_PASSWORD=dstore/POSTGRESQL_PASSWORD=$pp/g" /etc/dstore/dstore.conf
su postgres -c psql > /dev/null <<EOF
  CREATE USER $pu WITH PASSWORD '$pp';
  ALTER USER $pu SUPERUSER;
EOF

# Create postgis template
echo "Creating postgis template"
su postgres -c "createdb -E UTF8 -T template0 template_postgis" > /dev/null
su postgres -c "psql template_postgis <<EOF
  CREATE EXTENSION \"uuid-ossp\";
  CREATE EXTENSION postgis;
  UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template_postgis';  
EOF"
