#!/bin/bash

OS=$(cat /etc/os-release | grep -w NAME)

if [ "$OS" == 'NAME="Rocky Linux"' ]; then
        dnf install ceph-mds
elif [ "$OS" == 'NAME="Ubuntu"' ]; then
        apt install ceph-mds
else
        echo "OS is not Ubuntu or Rocky Linux"
        exit
fi

# Prompt for ceph.conf and keyring
while true; do
read -p "Is the /etc/ceph/ceph.conf file and the admin keyring on this host (yes/no): " response

if [[ "$response" == "no" ]]; then
    echo "Exiting..."
    exit 0
elif [[ "$response" == "yes" ]]; then
    echo "Continuing..."
    break
else
    echo "Invalid response. Please enter 'yes' or 'no'."
fi
done

# Gather current number of MDSs and add 1
BASE_HOSTNAME=$(hostname -s)
HOSTNAME=$BASE_HOSTNAME
COUNTER=1
DIR="/var/lib/ceph/mds/ceph-$HOSTNAME"

while [ -d "$DIR" ]; do
    HOSTNAME="${BASE_HOSTNAME}-${COUNTER}"
    DIR="/var/lib/ceph/mds/ceph-$HOSTNAME"
    ((COUNTER++))
done

# Create Keyring Directory and make Keyring
echo "Creating Keyring"
mkdir "$DIR"
chown ceph:ceph "$DIR"
ceph auth get-or-create mds.$HOSTNAME mon 'profile mds' mgr 'profile mds' mds 'allow *' osd 'allow *' > "$DIR/keyring"
chown ceph:ceph "$DIR/keyring"

# Open Firewall ports 
echo "Opening Firewall"
firewall-cmd --add-service={ceph,ceph-mon} --permanent
firewall-cmd --reload 

# Start MDS Service
echo "Starting MDS service"
systemctl enable --now ceph-mds@$HOSTNAME

ceph -s

echo -e "\e[1;31mmds-$HOSTNAME\e[0m has been \e[1;32madded\e[0m"