#!/usr/bin/env bash
set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

DOCKERFILE=${1:-Dockerfile}
ERRORS=0
WARNINGS=0

echo -e "${BLUE}=== Dockerfile Validation ===${NC}\n"

if [[ ! -f "$DOCKERFILE" ]]; then
    echo -e "${RED}✗ Error: $DOCKERFILE not found${NC}"
    exit 1
fi

echo -e "${BLUE}Validating: $DOCKERFILE${NC}\n"

# Check FROM
echo -e "${YELLOW}[1/5] Checking FROM instruction...${NC}"
if grep "^FROM" "$DOCKERFILE" | grep -q ":latest"; then
    echo -e "${YELLOW}⚠ Using :latest tag${NC}"
    ((WARNINGS++))
else
    echo -e "${GREEN}✓ Versioned base image${NC}"
fi

# Check non-root user
echo -e "\n${YELLOW}[2/5] Checking non-root user...${NC}"
if grep -qE "^USER [^root]" "$DOCKERFILE"; then
    echo -e "${GREEN}✓ Non-root user configured${NC}"
else
    echo -e "${RED}✗ No non-root USER (security risk)${NC}"
    ((ERRORS++))
fi

# Check HEALTHCHECK
echo -e "\n${YELLOW}[3/5] Checking HEALTHCHECK...${NC}"
if grep -q "^HEALTHCHECK" "$DOCKERFILE"; then
    echo -e "${GREEN}✓ HEALTHCHECK configured${NC}"
else
    echo -e "${YELLOW}⚠ No HEALTHCHECK${NC}"
    ((WARNINGS++))
fi

# Check multi-stage
echo -e "\n${YELLOW}[4/5] Checking multi-stage build...${NC}"
from_count=$(grep -c "^FROM" "$DOCKERFILE" || true)
if [[ $from_count -gt 1 ]]; then
    echo -e "${GREEN}✓ Multi-stage build ($from_count stages)${NC}"
else
    echo -e "${YELLOW}⚠ Single-stage build${NC}"
    ((WARNINGS++))
fi

# Check .dockerignore
echo -e "\n${YELLOW}[5/5] Checking .dockerignore...${NC}"
if [[ -f ".dockerignore" ]]; then
    echo -e "${GREEN}✓ .dockerignore present${NC}"
else
    echo -e "${YELLOW}⚠ .dockerignore missing${NC}"
    ((WARNINGS++))
fi

# Summary
echo -e "\n${BLUE}=== Summary ===${NC}"
if [[ $ERRORS -eq 0 ]] && [[ $WARNINGS -eq 0 ]]; then
    echo -e "${GREEN}✓ Excellent! No issues${NC}"
    exit 0
elif [[ $ERRORS -eq 0 ]]; then
    echo -e "${YELLOW}⚠ $WARNINGS warning(s)${NC}"
    exit 0
else
    echo -e "${RED}✗ $ERRORS error(s), $WARNINGS warning(s)${NC}"
    exit 1
fi
