#!/bin/bash

NAME=$1
PORT=$2

if [ -z "$NAME" ] || [ -z "$PORT" ]; then
    echo "Not all required parameters are defined!"
    exit 1
fi

CERT_PATH="/etc/letsencrypt/live"
NGINX_CONF_PATH="/etc/nginx/conf.d"

# check the required utilities
which nginx | grep -o nginx > /dev/null &&  echo "NGINX OK" || echo "You need the NGINX to be installed"
which docker | grep -o docker > /dev/null &&  echo "Docker OK" || echo "You need the Docker to be installed"
which certbot | grep -o certbot > /dev/null &&  echo "certbot OK" || echo "You need the Certbot to be installed"

# container
VOLUMES_DIR="/srv/$NAME"

if [ "$(docker ps -a | grep $NAME)" ]; then
    echo "Container '$NAME' exists"
    echo "Command for removing: docker stop $NAME && docker rm $NAME"
    echo "Command for removing volumes: rm -rf $VOLUMES_DIR"
else
    echo "Creating container '$NAME'"
    docker pull bgerp/bgerp && docker run -d --name $NAME --restart unless-stopped \
        -v $VOLUMES_DIR/data/mysql:/var/lib/mysql \
        -v $VOLUMES_DIR/data/filestorage:/opt/bgerp/filestorage \
        -v $VOLUMES_DIR/data/backup:/opt/bgerp/backup \
        -v $VOLUMES_DIR/conf:/opt/bgerp/conf \
        -v $VOLUMES_DIR/log:/opt/bgerp/log \
        -p 127.0.0.1:$PORT:9088 \
    bgerp/bgerp && docker logs $NAME
fi

# certificate
CERT_DIR="$CERT_PATH/$NAME"

if [ -d "$CERT_DIR" ]; then
    echo "Certificate in '$CERT_DIR' exists"
    echo "Command for removing: certbot delete --cert-name $NAME"
else
    echo "Requesting certificate '$NAME'"
    systemctl stop nginx
    certbot certonly --standalone --cert-name $NAME -d $NAME
    systemctl start nginx
fi

# nginx
NGINX_CONF_FILE="$NGINX_CONF_PATH/$NAME.conf"

if [ -f "$NGINX_CONF_FILE" ]; then
    echo "NGINX configuration '$NGINX_CONF_FILE' already exists"
else
    echo "Writing NGINX configuration '$NGINX_CONF_FILE'"
    echo "server {
    # generated by
    # https://github.com/Pingvin235/bgerp/blob/master/srcx/deploy/deploy.sh
    server_name    $NAME;
    access_log     /var/log/nginx/$NAME.access.log;
    location / {
        client_max_body_size    100m;
        proxy_pass              http://127.0.0.1:$PORT/;
        proxy_redirect          http:// https://;
        proxy_set_header        Host $NAME;
        proxy_set_header        Connection close;
        proxy_set_header        X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header        X-Real-IP \$remote_addr;
        proxy_read_timeout      300;
        gzip_proxied            any;
    }
    listen 443 ssl;
    listen [::]:443 ssl;
    ssl_certificate $CERT_DIR/fullchain.pem;
    ssl_certificate_key $CERT_DIR/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}
server {
    listen         80;
    listen         [::]:80;
    server_name    $NAME;
    return         301 https://$NAME\$request_uri;
}" > $NGINX_CONF_FILE
    systemctl reload nginx
fi
