#!/bin/bash

set -e

ROOT_PATH="$(cd "$(dirname "$0")" && pwd)"
HTTP_PORT="$1"
SITE_NAME="$2"

if [[ $HTTP_PORT -le 0 ]]
then
    echo "Incorrect http port: ${HTTP_PORT}"
    false
fi

if [[ -z "${SITE_NAME}" ]]
then
    echo "Incorrect site name: ${SITE_NAME}"
    false
fi

mkdir -p /etc/nginx/sites-available

cat << _EOF > "/etc/nginx/sites-available/${SITE_NAME}.conf"
server
{
    listen ${HTTP_PORT};
    server_name repo ${SITE_NAME};

    # download
    autoindex on;               # enable directory listing output
    autoindex_exact_size off;   # output file sizes rounded to kilobytes, megabytes, and gigabytes
    autoindex_localtime on;     # output local times in the directory

    location /
    {
        root ${ROOT_PATH};
    }

    #root ${ROOT_PATH};
}
_EOF

if [[ -e "/etc/nginx/sites-enabled/${SITE_NAME}.conf" ]]
then
    unlink "/etc/nginx/sites-enabled/${SITE_NAME}.conf"
fi

mkdir -p /etc/nginx/sites-enabled

ln -s "/etc/nginx/sites-available/${SITE_NAME}.conf" "/etc/nginx/sites-enabled/${SITE_NAME}.conf"

systemctl restart nginx
