#!/usr/bin/env bash
set -eo pipefail; [[ $DOKKU_TRACE ]] && set -x

case "$DOKKU_DISTRO" in
  debian)
    echo "%dokku ALL=(ALL) NOPASSWD:/usr/sbin/invoke-rc.d nginx reload, /usr/sbin/nginx -t" > /etc/sudoers.d/dokku-nginx
    ;;

  ubuntu)
    echo "%dokku ALL=(ALL) NOPASSWD:/etc/init.d/nginx reload, /usr/sbin/nginx -t" > /etc/sudoers.d/dokku-nginx
    ;;

  opensuse)
    echo "%dokku ALL=(ALL) NOPASSWD:/sbin/service nginx reload, /usr/sbin/nginx -t" > /etc/sudoers.d/dokku-nginx
    ;;

  arch)
    echo "%dokku ALL=(ALL) NOPASSWD:/usr/bin/systemctl reload nginx, /usr/sbin/nginx -t" > /etc/sudoers.d/dokku-nginx
    ;;
esac

chmod 0440 /etc/sudoers.d/dokku-nginx

# if dokku.conf has not been created, create it
if [[ ! -f /etc/nginx/conf.d/dokku.conf ]]; then
  cat<<EOF > /etc/nginx/conf.d/dokku.conf
include $DOKKU_ROOT/*/nginx.conf;

server_tokens off;

ssl_session_cache shared:SSL:20m;
ssl_session_timeout 10m;

ssl_ciphers EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;

EOF
fi

# allow users to override their server_names_hash_bucket_size
if [[ ! -f /etc/nginx/conf.d/server_names_hash_bucket_size.conf ]]; then
  echo 'server_names_hash_bucket_size 512;' >| /etc/nginx/conf.d/server_names_hash_bucket_size.conf
fi

# revert dokku group changes
gpasswd -a dokku adm
chgrp -R adm /var/log/nginx
gpasswd -M "" dokku
[[ -f /etc/logrotate.d/nginx ]] && sed -i -e 's/create 0640 www-data dokku/create 0640 www-data adm/g' /etc/logrotate.d/nginx

# patch broken nginx 1.8.0 logrotate
[[ -f /etc/logrotate.d/nginx ]] && sed -i -e 's/invoke-rc.d/service/g' /etc/logrotate.d/nginx

case "$DOKKU_DISTRO" in
  debian)
    NGINX_INIT="/usr/sbin/invoke-rc.d"
    "$NGINX_INIT" nginx start || "$NGINX_INIT" nginx reload
    ;;

  ubuntu)
    NGINX_INIT="/etc/init.d/nginx"
    "$NGINX_INIT" start || "$NGINX_INIT" reload
    ;;

  opensuse)
    NGINX_INIT="/sbin/service"
    "$NGINX_INIT" nginx start || "$NGINX_INIT" nginx reload
    ;;

  arch)
    NGINX_INIT="/usr/bin/systemctl"
    "$NGINX_INIT" start nginx || "$NGINX_INIT" reload nginx
    ;;
esac


