#!/bin/bash
# Copyright (c) 2000-2020 Synology Inc. All rights reserved.

if ! checkPlatformFunction SYNO_FEA_MULTIPATH; then
	SkipThisProject
	return
fi

SYSTEMD_DIR=/usr/lib/systemd/system
SYNO_SPACE_TARGET_WANTS=syno-space.target.wants

env CC="${CC}" CFLAGS="${CFLAGS}" LDFLAGS="${LDFLAGS}" ToolChainSysRoot=${ToolChainSysRoot} make install DESTDIR=${TmpInstDir} $InstallDevLayout

# We need to move kpartx_id to binary folder
mv ${TmpInstDir}/usr/lib/udev/kpartx_id ${TmpInstDir}/sbin/

[ -f ${TmpInstDir}/usr/lib/udev/rules.d/11-dm-mpath.rules ] && rm -rf ${TmpInstDir}/usr/lib/udev/rules.d/11-dm-mpath.rules
[ -f ${TmpInstDir}/usr/lib/udev/rules.d/11-dm-parts.rules ] && rm -rf ${TmpInstDir}/usr/lib/udev/rules.d/11-dm-parts.rules
[ -f ${TmpInstDir}/usr/lib/udev/rules.d/56-multipath.rules ] && rm -rf ${TmpInstDir}/usr/lib/udev/rules.d/56-multipath.rules
[ -f ${TmpInstDir}/usr/lib/udev/rules.d/66-kpartx.rules ] && rm -rf ${TmpInstDir}/usr/lib/udev/rules.d/66-kpartx.rules
[ -f ${TmpInstDir}/usr/lib/udev/rules.d/68-del-part-nodes.rules ] && rm -rf ${TmpInstDir}/usr/lib/udev/rules.d/68-del-part-nodes.rules
[ -f ${TmpInstDir}/${SYSTEMD_DIR} ] && rm -rf ${TmpInstDir}/${SYSTEMD_DIR}

# Remove unused files
[ -d ${TmpInstDir}/lib64/pkgconfig ] && rm -rf ${TmpInstDir}/usr/lib64/pkgconfig
[ -d ${TmpInstDir}/usr/include ] && rm -rf ${TmpInstDir}/usr/include
[ -d ${TmpInstDir}/usr/share ] && rm -rf ${TmpInstDir}/usr/share
[ -d ${TmpInstDir}/usr/share ] && rm -rf ${TmpInstDir}/usr/share

# Install Synology's own files
mkdir -p ${TmpInstDir}/usr/syno/sbin
mkdir -p ${TmpInstDir}/etc
mkdir -p ${TmpInstDir}/etc/init
mkdir -p ${TmpInstDir}/usr/lib/udev/rules.d
mkdir -p ${TmpInstDir}/${SYSTEMD_DIR}
mkdir -p ${TmpInstDir}/${SYSTEMD_DIR}/${SYNO_SPACE_TARGET_WANTS}

# install scripts
install -c -v -m 755 syno/script/multipathd_pre_start.sh ${TmpInstDir}/usr/syno/sbin/multipathd_pre_start.sh
install -c -v -m 755 syno/script/multipathd_startup_action.sh ${TmpInstDir}/usr/syno/sbin/multipathd_startup_action.sh

# install multipathd config
install -c -v -m 644 syno/conf/multipath.conf ${TmpInstDir}/etc/multipath.conf

# install udev rules
install -c -v -m 644 syno/udev/rules/50-syno-multipath.rules ${TmpInstDir}/usr/lib/udev/rules.d/50-syno-multipath.rules

# install systemd service
install -c -v -m 644 syno/service/multipathd.service ${TmpInstDir}${SYSTEMD_DIR}/multipathd.service
install -c -v -m 644 syno/service/multipathd_startup_action.service ${TmpInstDir}${SYSTEMD_DIR}/multipathd_startup_action.service

# link systemd wants
ln -s ../multipathd.service ${TmpInstDir}/${SYSTEMD_DIR}/${SYNO_SPACE_TARGET_WANTS}/multipathd.service
ln -s ../multipathd_startup_action.service ${TmpInstDir}/${SYSTEMD_DIR}/${SYNO_SPACE_TARGET_WANTS}/multipathd_startup_action.service


if [ "x$NOSTRIP" != "xNOSTRIP" ]; then
	find ${TmpInstDir}/lib64/ -type f | xargs $STRIP
	find ${TmpInstDir}/sbin/ -type f | xargs $STRIP
fi
