#!/bin/bash
# =============================================================================
# SCRIPT THIẾT LẬP QUYỀN BẢO MẬT CHO LARAVEL PROJECT
# Tạo bởi: Security Audit 2025-12-08
# Sử dụng: sudo bash secure_permissions.sh [project_path]
# =============================================================================

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Default project path
PROJECT_PATH="${1:-$(pwd)}"

echo -e "${GREEN}=== THIẾT LẬP QUYỀN BẢO MẬT ===${NC}"
echo "Project: $PROJECT_PATH"
echo "Thời gian: $(date)"
echo ""

# Kiểm tra project tồn tại
if [ ! -d "$PROJECT_PATH" ]; then
    echo -e "${RED}[ERROR] Thư mục không tồn tại: $PROJECT_PATH${NC}"
    exit 1
fi

# Kiểm tra có phải Laravel project không
if [ ! -f "$PROJECT_PATH/artisan" ]; then
    echo -e "${YELLOW}[WARNING] Không phải Laravel project (không tìm thấy artisan)${NC}"
    read -p "Tiếp tục? (y/n): " confirm
    if [ "$confirm" != "y" ]; then
        exit 0
    fi
fi

echo -e "${YELLOW}[1/6] Thiết lập owner...${NC}"
chown -R www-data:www-data "$PROJECT_PATH"
echo "  ✓ Owner: www-data:www-data"

echo -e "${YELLOW}[2/6] Thiết lập quyền thư mục (755)...${NC}"
find "$PROJECT_PATH" -type d -print0 | xargs -0 -P 4 chmod 755
echo "  ✓ Directories: 755"

echo -e "${YELLOW}[3/6] Thiết lập quyền file (644)...${NC}"
find "$PROJECT_PATH" -type f -print0 | xargs -0 -P 4 chmod 644
echo "  ✓ Files: 644"

echo -e "${YELLOW}[4/6] Bảo vệ file .env (600)...${NC}"
if [ -f "$PROJECT_PATH/.env" ]; then
    chmod 600 "$PROJECT_PATH/.env"
    echo "  ✓ .env: 600 (chỉ owner đọc được)"
else
    echo "  - .env không tồn tại"
fi

echo -e "${YELLOW}[5/6] Thiết lập quyền ghi cho storage...${NC}"
if [ -d "$PROJECT_PATH/storage" ]; then
    chmod -R 775 "$PROJECT_PATH/storage"
    find "$PROJECT_PATH/storage" -type d -exec chmod 775 {} \;
    echo "  ✓ storage/: 775"
fi

if [ -d "$PROJECT_PATH/bootstrap/cache" ]; then
    chmod -R 775 "$PROJECT_PATH/bootstrap/cache"
    echo "  ✓ bootstrap/cache/: 775"
fi

echo -e "${YELLOW}[6/6] Thiết lập quyền execute cho artisan...${NC}"
if [ -f "$PROJECT_PATH/artisan" ]; then
    chmod 755 "$PROJECT_PATH/artisan"
    echo "  ✓ artisan: 755"
fi

echo ""
echo -e "${GREEN}=== HOÀN THÀNH ===${NC}"
echo "Quyền đã được thiết lập an toàn cho: $PROJECT_PATH"
