#!/bin/bash

# Скрипт для удаления приложения Brabus из Azure Cloud

# Цвета для вывода
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Проверяем, установлен ли Azure CLI
if ! command -v az &> /dev/null; then
    echo -e "${RED}Azure CLI is not installed. Please install it before running the script.${NC}"
    echo "Instructions: https://docs.microsoft.com/en-us/cli/azure/install-azure-cli"
    exit 1
fi

# Проверяем, авторизован ли пользователь в Azure
echo -e "${YELLOW}Checking Azure authentication...${NC}"
az account show > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo -e "${YELLOW}Azure login required. Starting login process...${NC}"
    az login
    if [ $? -ne 0 ]; then
        echo -e "${RED}Azure login failed. Exiting.${NC}"
        exit 1
    fi
fi

# Загружаем переменные окружения
if [ -f .env ]; then
    echo -e "${GREEN}Loading environment variables from .env file${NC}"
    export $(grep -v '^#' .env | xargs)
else
    echo -e "${RED}.env file not found. Please enter the environment variables manually.${NC}"
    
    # Запрашиваем нужные переменные
    read -p "Enter the resource group name: " AZURE_RESOURCE_GROUP
    if [ -z "$AZURE_RESOURCE_GROUP" ]; then
        echo -e "${RED}Resource group name is required. Exiting.${NC}"
        exit 1
    fi
    
    read -p "Enter the container registry name (or press Enter to skip): " AZURE_CONTAINER_REGISTRY
    read -p "Enter the storage account name (or press Enter to skip): " AZURE_STORAGE_ACCOUNT
    read -p "Enter the Key Vault name (or press Enter to skip): " AZURE_KEY_VAULT_NAME
fi

# Запрашиваем подтверждение перед удалением
echo -e "${RED}WARNING: You are about to delete the following resources:${NC}"
echo -e "${RED}  - Container group: brabus-container-group in resource group ${AZURE_RESOURCE_GROUP}${NC}"

if [ ! -z "$AZURE_CONTAINER_REGISTRY" ]; then
    echo -e "${RED}  - Container Registry: ${AZURE_CONTAINER_REGISTRY}${NC}"
fi

if [ ! -z "$AZURE_STORAGE_ACCOUNT" ]; then
    echo -e "${RED}  - Storage Account: ${AZURE_STORAGE_ACCOUNT}${NC}"
fi

if [ ! -z "$AZURE_KEY_VAULT_NAME" ]; then
    echo -e "${RED}  - Key Vault: ${AZURE_KEY_VAULT_NAME}${NC}"
fi

read -p "Are you sure you want to continue? (y/n): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}Operation canceled by user.${NC}"
    exit 0
fi

# Удаляем группу контейнеров
echo -e "${YELLOW}Deleting container group...${NC}"
az container delete \
    --resource-group $AZURE_RESOURCE_GROUP \
    --name brabus-container-group \
    --yes

# Удаляем реестр контейнеров, если указан
if [ ! -z "$AZURE_CONTAINER_REGISTRY" ]; then
    echo -e "${YELLOW}Deleting container registry ${AZURE_CONTAINER_REGISTRY}...${NC}"
    az acr delete \
        --resource-group $AZURE_RESOURCE_GROUP \
        --name $AZURE_CONTAINER_REGISTRY \
        --yes
fi

# Удаляем учетную запись хранения, если указана
if [ ! -z "$AZURE_STORAGE_ACCOUNT" ]; then
    echo -e "${YELLOW}Deleting storage account ${AZURE_STORAGE_ACCOUNT}...${NC}"
    az storage account delete \
        --resource-group $AZURE_RESOURCE_GROUP \
        --name $AZURE_STORAGE_ACCOUNT \
        --yes
fi

# Удаляем Key Vault, если указан
if [ ! -z "$AZURE_KEY_VAULT_NAME" ]; then
    echo -e "${YELLOW}Deleting Key Vault ${AZURE_KEY_VAULT_NAME}...${NC}"
    
    # Сначала нужно изменить политику удаления, чтобы обойти защиту от удаления
    az keyvault update \
        --name $AZURE_KEY_VAULT_NAME \
        --resource-group $AZURE_RESOURCE_GROUP \
        --enable-purge-protection false \
        --enable-soft-delete false
    
    # Теперь можно удалить Key Vault
    az keyvault delete \
        --name $AZURE_KEY_VAULT_NAME \
        --resource-group $AZURE_RESOURCE_GROUP
fi

# Запрашиваем, нужно ли удалить всю группу ресурсов
read -p "Do you want to completely delete the resource group ${AZURE_RESOURCE_GROUP}? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}Deleting resource group ${AZURE_RESOURCE_GROUP}...${NC}"
    az group delete --name $AZURE_RESOURCE_GROUP --yes
fi

echo -e "${GREEN}Resource deletion completed!${NC}"
