#! /bin/bash

## Installation and setup autostart for Systemd based systems.

echo
echo "Start installation Block-Bad-IP"

echo "Copy executable bbip to /usr/local/bin"
cp -f bin/bbip /usr/local/bin
chmod 755 /usr/local/bin/bbip

echo "Copy start-script bbipd to /usr/local/bin"
cp -f bin/bbipd /usr/local/bin
chmod 755 /usr/local/bin/bbipd

if ! [ -d /etc/bbip ] ; then
    echo "Create configuration directory /etc/bbip"
    mkdir /etc/bbip
fi

echo "Copy examples of configuration files to /etc/bbip"
cp -f etc/bbip/* /etc/bbip

echo "Examples in /etc/bbip will be used as configuration files"
echo "only if configuration files not allready exist"

if ! [ -f /etc/bbip/config.xml ] ; then
    cp -f /etc/bbip/config-example.xml /etc/bbip/config.xml
    echo "Adjust to your needs /etc/bbip/config.xml"
fi

if ! [ -f /etc/bbip/trusted-dns.txt ] ; then
    cp -f /etc/bbip/trusted-dns-example.txt /etc/bbip/trusted-dns.txt
    echo "Adjust to your needs /etc/bbip/trusted-dns.txt"
fi

if ! [ -f /etc/bbip/trusted-ip.txt ] ; then
    cp -f /etc/bbip/trusted-ip-example.txt /etc/bbip/trusted-ip.txt
    echo "Adjust to your needs /etc/bbip/trusted-ip.txt"
fi

if ! [ -f /etc/bbip/setvar ] ; then
  cp -f /etc/bbip/setvar-example /etc/bbip/setvar
  echo "Adjust to your needs /etc/bbip/setvar"
fi

if ! [ -d /var/log/bbip ] ; then
    mkdir /var/log/bbip
    echo "Logfile /var/log/bbip/bbip.log"
fi

echo "Create man page"
cp -f man/bbip_en.1.gz /usr/share/man/man1/bbip.1.gz
mandb 1>/dev/null 2>/dev/null

## Check if systemctl availabel. need to setup autostart with Systemd.
systemctl --version 1>/dev/null 2>/dev/null

if [ $? -eq 0 ] ; then 
     
    if [ ! -e "/etc/systemd/system/bbip.service" ] ; then
        echo "Enable autostart per Systemd"

        chmod 644 /etc/bbip/bbip.service
        ln -s /etc/bbip/bbip.service /etc/systemd/system/bbip.service
        systemctl enable bbip

        echo "To start \"systemctl start bbip\""
    else
        echo "Autostart per Systemd is allready enabled"
    fi

else 
    echo "On your system systemctl not found. Please enable autostart manual"
fi

## Check if /sbin/iptables exist
IPT=`/sbin/iptables --version 2>/dev/null`
if [ ! $? -eq 0 ] ; then
    echo "ERROR /sbin/iptables not found"
fi
