#!/bin/bash

CHATROOMS_DIR="/groups"
MAX_LINES=50  # Set the maximum number of lines to display

# Function to check if the user is the owner of the chat room
function is_owner {
    local chatroom="$1"
    local logfile="$CHATROOMS_DIR/${chatroom}.log"
    
    if [ -f "$logfile" ]; then
        local owner=$(stat -c "%U" "$logfile")
        if [[ "$owner" == "$USER" ]]; then
            return 0  # User is the owner
        fi
    fi
    return 1  # User is not the owner
}

# Function to create a chat room
function create_chatroom {
    local chatroom="$1"
    local logfile="$CHATROOMS_DIR/${chatroom}.log"
    
    if [ -f "$logfile" ]; then
        echo "Chat room '$chatroom' already exists."
    else
        touch "$logfile"
        echo "Chat room '$chatroom' created."
    fi
}

# Function to delete a chat room
function delete_chatroom {
    local chatroom="$1"
    local logfile="$CHATROOMS_DIR/${chatroom}.log"
    
    if [ -f "$logfile" ]; then
        rm "$logfile"
        echo "Chat room '$chatroom' deleted."
    else
        echo "Chat room '$chatroom' does not exist."
    fi
}

# Function to create a private chat room
function create_private_chatroom {
    local chatroom="$1"
    local logfile="$CHATROOMS_DIR/${chatroom}.log"
    local users_file="$CHATROOMS_DIR/${chatroom}_users.txt"
    
    if [ -f "$logfile" ]; then
        echo "Private chat room '$chatroom' already exists."
    else
        touch "$logfile"
        touch "$users_file"
        echo "Private chat room '$chatroom' created."
    fi
}

# Function to add users to a private chat room
function add_user_to_private_room {
    local chatroom="$1"
    local user="$2"
    local users_file="$CHATROOMS_DIR/${chatroom}_users.txt"
    
    if [ -f "$users_file" ]; then
        echo "$user" >> "$users_file"
        echo "User '$user' added to private chat room '$chatroom'."
    else
        echo "Private chat room '$chatroom' does not exist."
    fi
}

# Function to check if a user has access to a private chat room
function user_has_access {
    local chatroom="$1"
    local user="$2"
    local users_file="$CHATROOMS_DIR/${chatroom}_users.txt"
    
    if [ -f "$users_file" ]; then
        if grep -q "^$user$" "$users_file"; then
            return 0  # User has access
        fi
    fi
    return 1  # User does not have access
}

# Check if a command is provided
if [ "$#" -lt 2 ]; then
    echo "Usage: $0 <command> <chatroom>"
    echo "Commands: create, delete, create_private, add_user, chat"
    exit 1
fi

COMMAND=$1
CHATROOM=$2
LOGFILE="$CHATROOMS_DIR/${CHATROOM}.log"

# Check if the user is the owner for create/delete commands
USER=$(whoami)

if [[ "$COMMAND" == "create" ]]; then
    create_chatroom "$CHATROOM"
    exit 0
elif [[ "$COMMAND" == "delete" ]]; then
    if is_owner "$CHATROOM"; then
        delete_chatroom "$CHATROOM"
        exit 0
    else
        echo "Permission denied: You do not own this chat room."
        exit 1
    fi
elif [[ "$COMMAND" == "create_private" ]]; then
    create_private_chatroom "$CHATROOM"
    exit 0
elif [[ "$COMMAND" == "add_user" ]]; then
    if is_owner "$CHATROOM"; then
        if [ "$#" -ne 3 ]; then
            echo "Usage: $0 add_user <chatroom> <username>"
            exit 1
        fi
        add_user_to_private_room "$CHATROOM" "$3"
        exit 0
    else
        echo "Permission denied: You do not own this private chat room."
        exit 1
    fi
elif [[ "$COMMAND" != "chat" ]]; then
    echo "Invalid command. Use 'create', 'delete', 'create_private', 'add_user', or 'chat'."
    exit 1
fi

# Create the log file if it doesn't exist
touch "$LOGFILE"

# Create a named pipe for the chat
FIFO="/tmp/chat_$CHATROOM.fifo"
if [ ! -p "$FIFO" ]; then
    mkfifo "$FIFO"
fi

# Check if the chat room is private and if the user has access
if [[ "$COMMAND" == "chat" ]]; then
    if [[ -f "$CHATROOMS_DIR/${CHATROOM}_users.txt" ]]; then
        if ! user_has_access "$CHATROOM" "$USER"; then
            echo "Permission denied: You do not have access to this private chat room."
            exit 1
        fi
    fi
fi

# Function to handle incoming messages
function read_chat {
    while true; do
        if read line < "$FIFO"; then
            echo "$line" >> "$LOGFILE"  # Log the message
            echo "$line"                  # Display the message in the console
        fi
    done
}

# Start reading chat in the background
read_chat &

# Main loop for sending messages
while true; do
    # Display chat log (last MAX_LINES lines)
    clear
    echo "Chat Room: $CHATROOM"
    echo "-------------------------"
    # Display the last MAX_LINES lines of the log file
    tail -n "$MAX_LINES" "$LOGFILE"
    
    # Read user input
    read -r message
    if [[ "$message" == ":q" ]]; then
        break
    fi

    # Format the message
    TIMESTAMP=$(date +"%Y-%m-%d %H:%M:%S")
    formatted_message="$TIMESTAMP [$USER]: $message"

    # Write to named pipe
    echo "$formatted_message" > "$FIFO"
done

# Clean up
rm "$FIFO"

