#!/bin/bash
set -o nounset                              # Treat unset variables as an error

echo "RUN $(basename "$0") ==="

DIR=$(realpath $(dirname $0)/..)
if [ ! -e $DIR/main.env ]
then
    echo "Please copy in root of NoCloud Auto Installer main.env.sample to main.env and edit it"
    exit 1
else
    echo "Environment file loaded"
fi
. $DIR/main.env


if [ -z "$(grep '^alias ls=' /root/.bashrc)" ]
then
    echo 'alias ls="ls -lstrh --color=auto"' >> /root/.bashrc
fi
cat <<EOF > /root/.vimrc
set bg=dark
colorscheme slate

set number
set relativenumber
set showcmd
" Define tabs size
set shiftwidth=4
set tabstop=4
" Replace tab by spaces
set expandtab
set smartindent
set smarttab
" Smartcase
set smartcase
set ignorecase
" Define line size
"set textwidth=78
set textwidth=0
set linebreak
set colorcolumn=80
highlight ColorColumn ctermbg=darkgrey

" Syntax coloration
syntax on
filetype plugin indent on
EOF

ignoreips=()

for domain in "${IGNORE_DOMAINS[@]}"; do
    # Use dig to get the IP address
    ip=$(dig +short "$domain")
    ignoreips=("${ignoreips[@]}" $ip)
    # Displays the domain name and IP addresss
    echo "$domain : $ip"
done

cat <<EOF > /etc/fail2ban/jail.local
[DEFAULT]

ignoreip = 127.0.0.1/8 ::1 ${ignoreips[@]} $(docker network inspect traefik | awk '/Subnet/{print $2}' | sed -e 's/"//g' -e 's/,$//')

EOF

fail2ban-client reload