#!/bin/bash

# Standardwerte setzen
TARGET=""
IP=$(ip a s enp0s3 | grep "inet\>" | awk '{ print $2 }' | cut -f 1 -d /)
# Optionen mit getopts parsen

while getopts "t:" opt; do
  case $opt in
    t) TARGET="$OPTARG" ;;
    *) echo "Ungueltige Option" >&2; exit 1 ;;
  esac
done


# Gueltigkeit pruefen
if [[ -z "$TARGET" ]]; then
  echo "Fehlendes TARGET! Nutzung:"
  echo "$0 -t <TARGET>"
  exit 1
fi

echo "Tabula Rasa" 
apt purge -y haproxy
rm -fr /etc/haproxy
echo "Install Haproxy"
apt install -y haproxy
echo "SSL Stuff"
mkdir -p /etc/haproxy/ssl
cat /etc/ssl/own.crt /etc/ssl/own.key > /etc/haproxy/ssl/revproxy.pem
chmod 600 /etc/haproxy/ssl/revproxy.pem
echo "Konfiguration anlegen"
cat<<HERE > /etc/haproxy/haproxy.cfg
global
    log /dev/log    local0
    log /dev/log    local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
    stats timeout 30s
    user haproxy
    group haproxy
    daemon
    ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384
    ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
    ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets

defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    timeout connect 5000
    timeout client  50000
    timeout server  50000
    errorfile 400 /etc/haproxy/errors/400.http
    errorfile 403 /etc/haproxy/errors/403.http
    errorfile 408 /etc/haproxy/errors/408.http
    errorfile 500 /etc/haproxy/errors/500.http
    errorfile 502 /etc/haproxy/errors/502.http
    errorfile 503 /etc/haproxy/errors/503.http
    errorfile 504 /etc/haproxy/errors/504.http

# Frontend: HTTPS
frontend ft_https
    bind $IP:443 ssl crt /etc/haproxy/ssl/revproxy.pem
    mode http
    option http-keep-alive
    option forwardfor
    timeout client 30s
    acl acl_revproxy hdr_beg(host) -i revproxy
    use_backend backend_www if acl_revproxy

# Frontend: HTTP → HTTPS Redirect
frontend ft_http
    bind $IP:80
    mode http
    option http-keep-alive
    timeout client 30s
    acl acl_http req.proto_http
    http-request redirect code 301 scheme https if acl_http

# Backend: www.it2XX.int
backend backend_www
    server www $TARGET:443 ssl verify none check
HERE
echo "Enable und Restart"
systemctl enable haproxy
systemctl restart haproxy
