#!/bin/sh

# Copyright (C) 2025-2026 Daniel Baumann <daniel@debian.org>
#
# SPDX-License-Identifier: GPL-3.0+
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

set -e

if [ -z "${1}" ]
then

cat << EOF
Usage: ${0} ACCOUNT SHARE

Examples:
  ${0} bad9 Users/bad9
  ${0} bad9 Services/Foo-bar
EOF

	exit 1
fi

PROGRAM="$(basename "${0}")"

BFH_USER="${1}"
BFH_SHARE="${2}"
BFH_SIZE="[${3}]"

DATE="$(date +%Y-%m-%d\ %H:%M:%S)"
HOST="$(hostname -f 2> /dev/null || hostname)"

echo "${DATE} ${HOST} ${PROGRAM} ${*}" >> "/var/log/bfh-ssp/bfh-ssp-tools.log"
irk "irc://irc.oftc.net:6668/bfh-linux-sysadmin" "\x0300${PROGRAM}\x03@\x0312${HOST}:\x03 \x0303${BFH_USER}\x03 \x0307${BFH_SHARE}\x03 ${BFH_SIZE}"

Clean ()
{
	# shellcheck disable=SC2317
	rm -f "${_TMPFILE}"
}

trap 'Clean' EXIT HUP INT QUIT TERM

_TMPFILE="$(mktemp -t bfh-ssp_"${PROGRAM}".XXXXXXXX)"

cat > "${_TMPFILE}" << EOF
From: ${PROGRAM}+noreply@${HOST}
To: bfh-linux-ssp@lists.bfh.science
Subject: ${PROGRAM}: ${BFH_USER} ${BFH_SHARE} ${BFH_SIZE}

Date: ${DATE}
Command: ${PROGRAM} ${@}
EOF

# shellcheck disable=SC2002
cat "${_TMPFILE}" | /usr/sbin/sendmail -t

DEPARTMENT="$(echo "${BFH_SHARE}" | awk -F/ '{ print $1 }')"
NAME="$(echo "${BFH_SHARE}" | awk -F/ '{ print $2 }')"

case "${DEPARTMENT}" in
	Users)
		# Create User share (/mnt/data/user/home/${BFH_USER})
		/usr/libexec/bfh/ceph-share --type user --name "${BFH_USER}" --quiet
		;;

	*)
		# Create LDAP group for write permissions (IDM.perm.storage.${DEPARTMENT}_${NAME}.write with owner ${BFH_USER} and member ${BFH_USER})
		RETURN="$(/usr/libexec/bfh/ldap-group --owners "${BFH_USER}" --users "${BFH_USER}" --type perm --service storage --department "${DEPARTMENT}" --name "${NAME}" --role write --quiet)"

		if [ -n "${RETURN}" ]
		then
			echo "${RETURN}"
			exit 0
		fi

		# Create LDAP group for read permissions (IDM.perm.storage.${DEPARTMENT}_${NAME}.read with owner ${BFH_USER})
		/usr/libexec/bfh/ldap-group --owners "${BFH_USER}" --type perm --service storage --department "${DEPARTMENT}" --name "${NAME}" --role read --owners "${BFH_USER}" --quiet

		# Create Group share (/mnt/data/group/${DEPARTMENT}/${NAME})
		/usr/libexec/bfh/ceph-share --type group --department "${DEPARTMENT}" --name "${NAME}" --quiet
		;;
esac
