#!/bin/bash

# Author: Jakub Konvicka
# Contact: jakub.konvicka@vsb.cz
# Web: https://heappe.eu/
# Support: support.heappe@it4i.cz
# Description: This script creates the directory structure for a new HEAppE project.

# Define the base path for the project directory
BASE_PATH="/opt/heappe"

echo "--------------------------------------------------------"
echo "HEAppE Middleware Environment directory structure setup"
echo "--------------------------------------------------------"

# Define the project directory variable
PROJECT_DIRECTORY=""

# Loop until a valid project directory name is provided
while [ -z "$PROJECT_DIRECTORY" ]; do
    # Prompt for project directory name if not provided as an argument
    if [ -z "$1" ]; then
        echo -n "Enter project directory name: "
        read PROJECT_DIRECTORY
    else
        PROJECT_DIRECTORY="$1"
    fi

    # Check if the project directory is empty
    if [ -z "$PROJECT_DIRECTORY" ]; then
        echo "Project directory name cannot be empty."
        continue
    fi

    # Check if the project directory already exists
    if [ -d "$BASE_PATH/projects/$PROJECT_DIRECTORY" ]; then
        echo "Project directory structure for $PROJECT_DIRECTORY already exists."
        PROJECT_DIRECTORY=""
    fi
done

echo "Creating structure for project: $PROJECT_DIRECTORY ..."

# Create the base directory if it doesn't exist
if [ ! -d "$BASE_PATH" ]; then
    echo "Creating base directory: $BASE_PATH ..."
    mkdir -p "$BASE_PATH"
    chmod -R 700 "$BASE_PATH"
fi

# Create subdirectories if they don't exist
cd "$BASE_PATH"
for subdir in projects confs; do
    if [ ! -d "$subdir" ]; then
        echo "Creating directory: $subdir ..."
        mkdir "$subdir"
        chmod -R 700 "$subdir"
    fi
done

# Create project directory structure
cd projects
if [ ! -d "$PROJECT_DIRECTORY" ]; then
    echo "Creating project directory structure for: $PROJECT_DIRECTORY ..."
    mkdir -p "$PROJECT_DIRECTORY/app/keys" \
             "$PROJECT_DIRECTORY/app/logs" \
             "$PROJECT_DIRECTORY/app/confs" \
             "$PROJECT_DIRECTORY/ssh_agent/keys" \
             "$PROJECT_DIRECTORY/docker_configurations"
    chmod -R 700 "$PROJECT_DIRECTORY"
    echo "Project directory structure created successfully."
else
    echo "Project directory structure for $PROJECT_DIRECTORY already exists."
    exit 255
fi