#!/bin/bash

# Function to modify the existing JazManager module
modify_existing_module() {
    echo "Enter the new menu name for the existing JazManager module:"
    read new_menu_name

    echo "Choose an option to go the JazManager:"
    echo "1) Switch from the Zabbix screen to the JazManager screen"
    echo "2) Open the JazManager screen in a new browser tab"
    
    read option

    case $option in
        1)
            modify_existing_module_with_same_transition
            echo "Existing JazManager module updated with the new menu name."
            ;;
        2)
            modify_existing_module_with_new_tab_transition
            echo "Existing JazManager module updated with the new menu name."
            ;;
        *)
            echo "Invalid option."
            ;;
    esac
}

modify_existing_module_with_same_transition() {
    # Modify the function block with a precise `sed` command with the same transition
    sed -i "/public function init(): void/ {
        :a; N; /}/!ba;
        s|public function init(): void.*|public function init(): void\n    {\n        APP::Component()->get('menu.main')\n            ->add((new CMenuItem(_('Jaz Manager')))\n                ->setIcon(ZBX_ICON_COMMAND)\n                ->setSubMenu(new CMenu([\n                    (new CMenuItem(_('$new_menu_name')))\n                        ->setAction('jaz.manager.app')\n                ])));\n    }|
    }" ./JazManager/Module.php
}

modify_existing_module_with_new_tab_transition() {
    # Modify the function block with a precise `sed` command with the transition to a new tab
    sed -i "/public function init(): void/ {
        :a; N; /}/!ba;
        s|public function init(): void.*|public function init(): void\n    {\n        \$url = new CUrl('zabbix.php');\n        \$url->setArgument('action', 'jaz.manager.app');\n\n        APP::Component()->get('menu.main')\n            ->add((new CMenuItem(_('Jaz Manager')))\n                ->setIcon(ZBX_ICON_COMMAND)\n                ->setSubMenu(new CMenu([\n                    (new CMenuItem(_('$new_menu_name')))\n                        ->setUrl(\$url)\n                        ->setTarget('_blank')\n                ])));\n    }|
    }" ./JazManager/Module.php
}


# Function to create a new JazManager module
create_new_module() {
    while true; do
        echo "Enter the new unique module ID (e.g., jaz_example_app):"
        read new_id

        # Check if the input matches snake_case (lowercase letters, numbers, and underscores only)
        if [[ "$new_id" =~ ^[a-z][a-z0-9_]*[a-z0-9]$ ]]; then
            break
        else
            echo "Invalid ID. Please use only lowercase letters, and underscores (e.g., jaz_example_app)."
        fi
    done

    echo "Enter the new menu name for the new JazManager module:"
    read new_menu_name

    echo "Choose an option to go the JazManager:"
    echo "1) Switch from the Zabbix screen to the JazManager screen"
    echo "2) Open the JazManager screen in a new browser tab"
    
    read option

    # Validate immediately
    case $option in
        1|2)
            ;;
        *)
            echo "Invalid option."
            exit 1
            ;;
    esac

    echo "Enter the new Jaz URL (optional, press Enter to skip):"
    read new_url

    echo "Enter new description (optional, press Enter to keep default):"
    read new_description

    new_folder_name=$new_id

    new_name=$(echo "$new_id" | awk -F'_' '{for (i=1; i<=NF; i++) $i=toupper(substr($i,1,1)) substr($i,2)} 1' OFS=' ')

    new_namespace=$(echo "$new_id" | awk -F'_' '{for (i=1; i<=NF; i++) $i=toupper(substr($i,1,1)) substr($i,2)} 1' OFS='')

    new_action=${new_id//_/.}

    new_description=${new_description:-"Redirects to $new_id"}

    # Step 1: Duplicate the JazManager folder
    cp -R ./JazManager ./"$new_folder_name"

    # Step 2: Modify the Module.php in the new folder
    sed -i "s/namespace Modules\\\\JazManager;/namespace Modules\\\\$new_namespace;/g" ./"$new_folder_name"/Module.php

    case $option in
        1)
            create_new_module_with_same_transition
            ;;
        2)
            create_new_module_with_new_tab_transition
            ;;
        *)
            ;;
    esac

    # Step 3: Modify the manifest.json
    sed -i "s/\"id\": \"jaz-manager\"/\"id\": \"$new_id\"/g" ./"$new_folder_name"/manifest.json
    sed -i "s/\"name\": \"JAZ Manager\"/\"name\": \"$new_name\"/g" ./"$new_folder_name"/manifest.json
    sed -i "s/\"namespace\": \"JazManager\"/\"namespace\": \"$new_namespace\"/g" ./"$new_folder_name"/manifest.json
    sed -i "s/\"jaz.manager.app\":/\"$new_action\":/g" ./"$new_folder_name"/manifest.json

    # Step 4: Modify the namespace in actions/JazManagerApp.php
    sed -i "s/namespace Modules\\\\JazManager\\\\Actions;/namespace Modules\\\\$new_namespace\\\\Actions;/g" ./"$new_folder_name"/actions/JazManagerApp.php

    # Step 5: Modify config/jam.module.config.php if Jaz URL is provided
    if [ ! -z "$new_url" ]; then
        sed -i "s|define('JAM_URL'.*);|define('JAM_URL' , '$new_url');|g" "./$new_folder_name/config/jam.module.config.php"
    fi

    # Step 6: Modify the description in manifest.json if provided
    if [ ! -z "$new_description" ]; then
        sed -i "s/\"description\": \"Redirects to Job Arranger Manager Application.\"/\"description\": \"$new_description\"/g" ./"$new_folder_name"/manifest.json
    fi

    case $option in
        1|2)
            echo "New JazManager module created successfully in the folder: $new_folder_name"
            ;;
        *)
            ;;
    esac
}

create_new_module_with_same_transition() {
    # Overwrite the init function in the new Module.php with the same transition
    sed -i "/public function init(): void/{:a;N;/}/!ba; s|public function init(): void.*|public function init(): void\n    {\n        \$jazMenu = APP::Component()->get('menu.main')\n            ->find(_('Jaz Manager'));\n        \$subMenuItems = \$jazMenu->getSubMenu()->getMenuItems();\n        \$newSubMenu = (new CMenuItem(_('${new_menu_name}')))\n            ->setAction('${new_action}');\n        \$jazMenu->getSubMenu()->insertAfter(\n            \$subMenuItems[array_key_last(\$subMenuItems)]->getLabel(),\n            \$newSubMenu\n        );\n    }|}" ./"$new_folder_name"/Module.php
}

create_new_module_with_new_tab_transition() {
    # Overwrite the init function in the new Module.php with the transition to a new tab
    sed -i "/public function init(): void/{:a;N;/}/!ba; s|public function init(): void.*|public function init(): void\n    {\n        \$jazMenu = APP::Component()->get('menu.main')\n            ->find(_('Jaz Manager'));\n        \$url = new CUrl('zabbix.php');\n        \$url->setArgument('action', '${new_action}');\n\n        \$subMenuItems = \$jazMenu->getSubMenu()->getMenuItems();\n        \$newSubMenu = (new CMenuItem(_('${new_menu_name}')))\n            ->setUrl(\$url)\n            ->setTarget('_blank');\n        \$subMenuItems = \$jazMenu->getSubMenu()->getMenuItems();\n        \$jazMenu->getSubMenu()->insertAfter(\n            \$subMenuItems[array_key_last(\$subMenuItems)]->getLabel(),\n            \$newSubMenu\n        );\n    }|}" ./"$new_folder_name"/Module.php
}

# Check only inside the use block
if ! awk '/^use /,/;/' ./JazManager/Module.php | grep -q "CUrl"; then
    sed -i '/CMenuItem;/s/;/,\
    CUrl;/' ./JazManager/Module.php
fi

# Main script
echo "Choose an option:"
echo "1) Modify the existing JazManager module for multi-setup"
echo "2) Create a new JazManager module for multi-setup"

read option

case $option in
    1)
        modify_existing_module
        ;;
    2)
        create_new_module
        ;;
    *)
        echo "Invalid option."
        ;;
esac
