#!/bin/bash

# EN: OS Detection and Compatibility Helper
# VI: Helper phát hiện Hệ điều hành và Tương thích

OS="$(uname -s)"
case "${OS}" in
    Linux*)     OS_TYPE=Linux;;
    Darwin*)    OS_TYPE=Mac;;
    CYGWIN*)    OS_TYPE=Cygwin;;
    MINGW*)     OS_TYPE=MinGw;;
    *)          OS_TYPE="UNKNOWN:${OS}"
esac

# EN: Logging function
# VI: Hàm logging
log_info() {
    echo -e "\033[0;32m[INFO]\033[0m $1"
}

log_warn() {
    echo -e "\033[1;33m[WARN]\033[0m $1"
}

# EN: Cross-platform SED command
# VI: Lệnh SED đa nền tảng
# Usage: run_sed "s/find/replace/g" filename
run_sed() {
    if [ "$OS_TYPE" = "Mac" ]; then
        sed -i '' "$1" "$2"
    else
        sed -i "$1" "$2"
    fi
}

# EN: Cross-platform OPEN command (open URL or file)
# VI: Lệnh OPEN đa nền tảng (mở URL hoặc file)
run_open() {
    if [ "$OS_TYPE" = "Mac" ]; then
        open "$1"
    elif [ "$OS_TYPE" = "Linux" ]; then
        xdg-open "$1"
    else
        echo "Cannot open $1 on $OS_TYPE"
    fi
}

export OS_TYPE
export -f run_sed
export -f run_open
export -f log_info
export -f log_warn

# EN: Cross-platform Docker Compose command
# VI: Lệnh Docker Compose đa nền tảng
run_compose() {
    if command -v docker-compose &> /dev/null; then
        docker-compose "$@"
    elif docker compose version &> /dev/null; then
        docker compose "$@"
    else
        echo -e "\033[0;31m[ERROR]\033[0m Docker Compose not found / Không tìm thấy Docker Compose"
        return 1
    fi
}

export -f run_compose
