#!/bin/bash

# Tentukan apakah perlu membangun ulang Docker
build_docker=${1:-false}
os_type=$(uname | sed 's/-.*//')
echo "OS Type: ${os_type}"

# Array asosiatif untuk domain
declare -A domains=(
    [web]='test.usdt_currency.com'
    [www]='www.test.usdt_currency.com'
    [two]='two.test.usdt_currency.com'
    [api]='api.test.usdt_currency.com'
)

# Tentukan lokasi file hosts berdasarkan sistem operasi
case "$os_type" in
    Linux|Darwin) hosts_file="/etc/hosts" ;;
    MINGW32_NT|MINGW64_NT|CYGWIN) hosts_file="C:\\Windows\\System32\\drivers\\etc\\hosts" ;;
    *) echo "Sistem operasi tidak didukung." && exit 1 ;;
esac

add_hosts_entry() {
    local host_entry=$1
    local file_path=$2
    host_entry="127.0.0.1   $host_entry"
    if ! grep -q "$host_entry" "$file_path"; then
        echo "Menambahkan $host_entry ke $file_path"
        if [[ "$os_type" == "Linux" || "$os_type" == "Darwin" ]]; then
            echo "$host_entry" | sudo tee -a "$file_path" > /dev/null
        elif [[ "$os_type" == "MINGW32_NT" || "$os_type" == "MINGW64_NT" || "$os_type" == "CYGWIN" ]]; then
            windows_path=$(echo "$file_path" | sed 's|/|\\|g')
            echo "Menjalankan PowerShell untuk menambahkan entry ke hosts..."
            powershell_output=$(powershell -Command "Start-Process PowerShell -ArgumentList '-NoExit', '-Command', \"Add-Content -Path '$windows_path' -Value '$host_entry'; exit\" -Verb RunAs" 2>&1)
        fi
    else
        echo "Domain $host_entry sudah ada di $file_path"
    fi
}

for key in "${!domains[@]}"; do
    add_hosts_entry "${domains[$key]}" "$hosts_file"
done

if [[ "$build_docker" == "true" ]]; then
    echo "Menjalankan docker-compose up dengan build..."
    docker-compose up --build
else
    echo "Menjalankan docker-compose up tanpa build..."
    docker-compose up
fi
