#!/bin/bash
#
# Provisioner for a simple hosting environment
#

# Parameters
PROJECT="${PROJECT:-bookup}"

# Check for sudo
if [ "`whoami`" != "root" ]; then
  SUDO="sudo"
fi

# Apache
$SUDO apt install -y apache2

# Configure an Onion Service
if which trashman &> /dev/null; then
  trashman install tor-onion-service
else
  HIDDEN="/var/lib/tor/hidden/${PROJECT}"

  # Install Tor
  $SUDO apt install -y tor

  # Tor config
  cat <<-EOF | $SUDO tee -a /etc/tor/torrc > /dev/null
RunAsDaemon 1
HiddenServiceDir $HIDDEN
HiddenServicePort 80 127.0.0.1:80
EOF

  # Create folder structure
  $SUDO mkdir -p $HIDDEN
  $SUDO chmod -R 700 $HIDDEN
  $SUDO chown -R debian-tor: $HIDDEN

  # Start Tor
  $SUDO service tor restart
fi

# Configure Onion Service virtual host
cat <<-EOF | $SUDO tee /etc/apache2/sites-available/onion.conf > /dev/null
<VirtualHost 127.0.0.1:80>
    ServerName localhost
    ServerAlias *.onion
    DocumentRoot "/srv/shared/compiled"

    <Directory /srv/shared/compiled>
      #AuthType Basic
      #AuthName "Protected"
      #AuthUserFile /srv/shared/.htpasswd
      #Require valid-user
      Options Indexes FollowSymLinks
      AllowOverride All
      Require all granted
    </Directory>
</VirtualHost>
EOF

# Configure local virtual host
cat <<-EOF | $SUDO tee /etc/apache2/sites-available/local.conf > /dev/null
<VirtualHost *:80>
    ServerName ${PROJECT}.local
    DocumentRoot "/srv/shared/compiled"

    <Directory /srv/shared/compiled>
      #AuthType Basic
      #AuthName "Protected"
      #AuthUserFile /srv/shared/.htpasswd
      #Require valid-user
      Options Indexes FollowSymLinks
      AllowOverride All
      Require all granted
    </Directory>
</VirtualHost>
EOF

# Ensure that the DocumentRoot exists
$SUDO mkdir -p /srv/shared

# Enable virtual host
$SUDO a2ensite onion local
$SUDO service apache2 restart