#!/bin/bash

MIN_SSH_PORT=41000
MAX_SSH_PORT=43999
MIN_WEB_PORT=51000
MAX_WEB_PORT=53999

certificate="--tlsverify --tlscacert=/root/.docker/ca.pem --tlscert=/root/.docker/cert.pem --tlskey=/root/.docker/key.pem -H=127.0.0.1:2376"

extract_port(){
  first="$1"
  if [[ "$1" =~ ^80.* || "$1" =~ ^22.* ]]; then
	port=${first//80\/}
	port=${port//22\/}
	echo $port
  fi
}

# Iterate over all containers and retrive their ports.
get_busy_ports(){
  sudo docker $certificate ps | awk '{ print $NF }' | awk 'NR>1' | while read line; do
    port_mapping="$(sudo docker $certificate port $line)" 
    ports=${port_mapping//tcp -> 0.0.0.0:} 
    first_port="$(echo $ports | awk '{ print $1 }')"
    second_port="$(echo $ports | awk '{ print $2 }')"
    busy_ports+=" $(extract_port $first_port) "
    busy_ports+=" $(extract_port $second_port) "
    echo "$busy_ports"
  done
}

# Get the name of the service (WEB|SSH)
# and return the first available port.
# param $1 string 
get_free_port(){
  # service can be WEB|SSH
  service=$1
  if [ $1 = "WEB" ]; then
    used_port=$MIN_WEB_PORT
    MIN_SERVICE_PORT=$MIN_WEB_PORT
    MAX_SERVICE_PORT=$MAX_WEB_PORT
  elif [ $1 = "SSH" ]; then
    used_port=$MIN_SSH_PORT
    MIN_SERVICE_PORT=$MIN_SSH_PORT
    MAX_SERVICE_PORT=$MAX_SSH_PORT
  fi  

  # Get a mixed list of used ports ssh/web.    
  busy_ports=(`echo "$(get_busy_ports)"`)

  for port in "${busy_ports[@]}"
  do
    if [[ $port -ge $MIN_SERVICE_PORT && $port -le $MAX_SERVICE_PORT ]]; then
      if [[ $port -gt $used_port ]]; then
        let used_port=$port
      fi
    fi
  done

  if [[ $used_port = $MAX_SERVICE_PORT ]]; then
     echo "ERROR: ports reached limit" 1>&2
     exit 1
  fi

  echo $((used_port+1))  
}

# Get name and port and create a virtualhost proxypass
# param1 $1 container name
# param 2 int port
create_virtualhost(){
  container_name=$1
  web_port=$2

  echo "<VirtualHost ${container_name}.eae.pt:80> 
    ServerName ${container_name}.eae.pt 
    ProxyPass / http://${container_name}.eae.pt:${web_port}/ retry=1 acquire=3000 timeout=600 Keepalive=On
    #ProxyPassReverse / http://${container_name}.eae.pt/
    ProxyPreserveHost On
    ProxyRequests Off
    ProxyVia Off
   </VirtualHost>" >>  /etc/apache2/sites-available/$container_name.conf

  echo "<IfModule mod_ssl.c>
<VirtualHost ${container_name}.eae.pt:443>
    ServerName ${container_name}.eae.pt
    RequestHeader set X-Forwarded-Proto "https"
    ProxyPass / http://${container_name}.eae.pt:${web_port}/ retry=1 acquire=3000 timeout=600 Keepalive=On
    #ProxyPassReverse / http://${container_name}.eae.pt/
    ProxyPreserveHost On
    ProxyRequests Off
    ProxyVia Off
    SSLEngine on
    SSLCertificateFile /etc/apache2/ssl/eae/eae.crt
    SSLCertificateKeyFile /etc/apache2/ssl/eae/eae.key
    SSLCertificateChainFile /etc/apache2/ssl/eae/alphassl.crt
</VirtualHost>
</IfModule>" >>  /etc/apache2/sites-available/$container_name-ssl.conf


  a2ensite $container_name.conf
  a2ensite $container_name-ssl.conf
  service apache2 reload  
}

# Return a well formatted output with all the info about the container
output_container_info(){
  echo "################################"
  echo "################################"
  echo "CONTAINER INFO" 
  echo "container name: $1"
  echo "ssh port: $2"
  echo "web port: $3"
  echo "domain: $1.eae.pt"
  echo "ssh connection string: ssh -p $2 eae@$1.eae.pt"
  echo "http user: $1"
  echo "http password: $4"
  echo "################################"
  echo "################################"
}

# Create a container giving the name and the image
# $1: string with the conatiner name
# $2: string with the image name
create_container(){
  last_web_port="$(get_free_port 'WEB')"
  last_ssh_port="$(get_free_port 'SSH')"
  container_name=$1
  container_image=$2
  container_password="$1eae2021"

  htpasswd -b -c /var/www/$container_name/access/.htpasswd $container_name $container_password

  docker $certificate run --restart=always -it -d --hostname $container_name --name $container_name  -v /var/ssh_team:/home/eae/.ssh -p $last_web_port:80 -p $last_ssh_port:22 -v /var/www/$container_name/html:/var/www/html -v /var/www/$container_name/cron:/etc/cron.d -v /var/www/$container_name/access:/var/www/access -m 1G --memory-swap 2G $container_image

  echo "docker $certificate run --restart=always -it -d --hostname $container_name --name $container_name  -v /var/ssh_team:/home/eae/.ssh -p $last_web_port:80 -p $last_ssh_port:22 -v /var/www/$container_name/html:/var/www/html -v /var/www/$container_name/cron:/etc/cron.d -v /var/www/$container_name/access:/var/www/access -m 1G  --memory-swap 2G $container_image" >> /var/www/Dockerfiles/containers/$container_name

  create_virtualhost $container_name $((last_web_port))
  output_container_info $container_name $last_ssh_port $last_web_port $container_password 
}

