#!/bin/sh

# Create directories
mkdir -p /usr/lib64/maxscale
mkdir -p /usr/bin
mkdir -p /usr/share/maxscale
mkdir -p /usr/share/doc/MaxScale/maxscale

# MAXSCALE_VARDIR is an absolute path to /var by default
mkdir -p /var/log/maxscale
mkdir -p /var/lib/maxscale
mkdir -p /var/cache/maxscale
mkdir -p /var/run/maxscale

# Create MaxScale user
if [ -f "/etc/passwd" ] && [ "$(grep -c 'maxscale' /etc/passwd)" -eq 0 ]
then
    groupadd -r maxscale
    useradd -r -s /bin/false -g maxscale maxscale
fi

# Change the owner of the directories to maxscale:maxscale
chown -R maxscale:maxscale /var/log/maxscale
chown -R maxscale:maxscale /var/lib/maxscale
chown -R maxscale:maxscale /var/cache/maxscale
chown -R maxscale:maxscale /var/run/maxscale
chmod 0755 /var/log/maxscale
chmod 0755 /var/lib/maxscale
chmod 0755 /var/cache/maxscale
chmod 0755 /var/run/maxscale

# Create the module configuration directory (default: /etc/maxscale.modules.d/)
mkdir -p /etc/maxscale.modules.d

# Install ldconfig files
if [ -f "/usr/share/maxscale/maxscale.conf" ]
then
    cp /usr/share/maxscale/maxscale.conf /etc/ld.so.conf.d/
else
    echo "Could not find ldconfig file: /usr/share/maxscale/maxscale.conf" >& 2
fi

# Only copy the service files if the systemd folder and systemctl executable are found
if [ -f /usr/share/maxscale/maxscale.service ] && command -v systemctl >/dev/null
then
    if [ -d "/lib/systemd/system"  ]
    then
        cp /usr/share/maxscale/maxscale.service /lib/systemd/system
        systemctl daemon-reload
    elif [ -d "/usr/lib/systemd/system"  ]
    then
        cp /usr/share/maxscale/maxscale.service /usr/lib/systemd/system
        systemctl daemon-reload
    fi
else
    if [ -d "/etc/init/" ]
    then
        cp /usr/share/maxscale/upstart/maxscale.conf /etc/init/
    fi

    # If systemd is not present, use init.d scripts
    if [ -f "/usr/share/maxscale/maxscale" ]
    then
        cp /usr/share/maxscale/maxscale /etc/init.d/
    else
        echo "Could not find init script: /usr/share/maxscale/maxscale" >& 2
    fi
fi

# If no maxscale.cnf file is found in /etc, copy the template file there
if [ ! -f "/etc/maxscale.cnf" ]
then
    cp /etc/maxscale.cnf.template /etc/maxscale.cnf
fi

# This will allow us to install the Perl scripts as executable files
# without adding the Perl dependencies
find /usr/share/maxscale/plugins/nagios -name '*.pl' -exec chmod ug+x {} \;

/sbin/ldconfig
