#!/bin/sh
#
# Copyright 2017, SUSE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

cmd=$1
workercount=${2:-auto}
vhostconfig=/etc/apache2/vhosts.d/chef-server-cluster.conf
serverconfig=/etc/sysconfig/chef-server
webroot=/srv/www/chef-server-cluster

baseport=4001

balancerstart=BEGIN-BALANCER-MEMBER
balancerend=END-BALANCER-MEMBER

usage() {
  echo "usage: chef-server-cluster <enable|disable> [<workercount>|auto]"
  exit 1
}

case $cmd in
  enable)
    [ "$workercount" == "auto" ] && workercount=$(grep -c ^processor /proc/cpuinfo)
    [ "$workercount" -ge 2 ] || { echo "ERROR: workercount must be >= 2"; exit 2; }

    # apache configuration
    mkdir -p "$webroot"
    a2enmod -q proxy_balancer || a2enmod proxy_balancer
    a2enmod -q lbmethod_byrequests || a2enmod lbmethod_byrequests
    tmpvhostconfig=$(mktemp)
    test -e "$vhostconfig" && cp "$vhostconfig" "$tmpvhostconfig" || cat <<EOF > $tmpvhostconfig
# configuration generated by: chef-server-cluster script
Listen 4000

<VirtualHost *:4000>
  DocumentRoot /srv/www/chef-server-cluster
  ErrorLog /var/log/apache2/chef-server-cluster-error.log
  CustomLog /var/log/apache2/chef-server-cluster-access.log combined

  <Location />
    Require all granted
  </Location>

  <Proxy balancer://chefworkers>
    # $balancerstart
    # $balancerend
    ProxySet failontimeout=On
  </Proxy>

  <Location /balancer-manager>
    SetHandler balancer-manager
    Require host localhost
    Require host 127.0.0.1
  </Location>

  RewriteEngine On
  RewriteCond %{REQUEST_URI} !=/balancer-manager
  RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
  RewriteRule ^/(.*)$ balancer://chefworkers%{REQUEST_URI} [P,QSA,L]
</VirtualHost>
EOF

    awk -i inplace "
      /$balancerstart/ { print; f=1} !f;
      /$balancerend/ {
        for (i=$baseport;i<$baseport+$workercount;i++) {
          print \"    BalancerMember http://127.0.0.1:\"i
        };
        print;
        f=0
      }
    " "$tmpvhostconfig"

    # chef-server configuration
    tmpserverconfig=$(mktemp)
    cat <<EOF > $tmpserverconfig
# configuration generated by: chef-server-cluster script
PORT=$baseport
OPTIONS="-N -c $workercount"
EOF

    if cmp -s "$serverconfig" "$tmpserverconfig"; then
      rm "$tmpserverconfig"
    else
      test -e "$serverconfig" && mv "$serverconfig" "$serverconfig.old"
      mv "$tmpserverconfig" "$serverconfig"
      systemctl restart chef-server
    fi

    if cmp -s "$vhostconfig" "$tmpvhostconfig"; then
      rm "$tmpvhostconfig"
    else
      mv "$tmpvhostconfig" "$vhostconfig"
      systemctl reload apache2
    fi
    echo "chef-server cluster enabled with $workercount workers."
  ;;

  disable)
    if test -f "$vhostconfig"; then
      mv "$vhostconfig" "$vhostconfig.disabled"
      systemctl reload apache2
    fi
    if test -f "$serverconfig"; then
      mv "$serverconfig" "$serverconfig.disabled"
      systemctl restart chef-server
    fi
    echo "chef-server cluster disabled."
  ;;

  *)
    usage
  ;;
esac
