#!/bin/bash

copy_if_not_exists() {
    local src="$1"  # src filename
    local dst="$2"  # dst dirname
    if [ ! -f "$dst/$src" ]; then
        cp $src $dst
    else
        echo "INFO: skipping copying $src since destination already exists."
    fi
}

if [ $(id -u) -ne 0 ]; then
    echo "You need super user privileges to run this script."
    exit 1
fi

echo "Running installer for centos"

echo "Stopping the AC NVM service..."
systemctl stop acnvm  >/dev/null 2>&1

useradd -r -s /bin/false acnvm

echo "Removing obsolete files..."
rm -f /usr/local/bin/acnvmcollector

echo "Copying files..."
ACNVM_PATH="/opt/acnvm"

mkdir -p /var/run/acnvm
chown acnvm:acnvm /var/run/acnvm

mkdir -p $ACNVM_PATH
mkdir -p $ACNVM_PATH/bin
mkdir -p $ACNVM_PATH/lib
mkdir -p $ACNVM_PATH/conf
mkdir -p $ACNVM_PATH/logs

cp acnvmcollector $ACNVM_PATH/bin
cp acnvmcolldiag  $ACNVM_PATH/bin

cp -R preload $ACNVM_PATH/bin
cp uninstall.sh $ACNVM_PATH/bin

copy_if_not_exists acnvm.conf    $ACNVM_PATH/conf
copy_if_not_exists acnvmlog.conf $ACNVM_PATH/conf
cp acnvmcolldiagconf.json $ACNVM_PATH/conf


chown -R acnvm:acnvm $ACNVM_PATH

ldconfig

echo "starting acnvmcollector..."

echo "systemd detected"
cp acnvm.service /etc/systemd/system
systemctl enable acnvm
systemctl start acnvm
ps aux | grep acnvm

