#!/bin/bash
# Auto-build script: Pull latest Memos code and build as Canifa Note
# Usage: ./auto-build.sh [optional-tag]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_NAME="${APP_NAME:-canifa-note}"
APP_ICON="${APP_ICON:-canifa}"
IMAGE_TAG="${1:-latest}"
REGISTRY="${REGISTRY:-}"  # e.g., "myregistry.azurecr.io" or empty for local

# Color output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${BLUE}=== Canifa Note Auto-Build Script ===${NC}"

# Step 1: Update code
echo -e "${YELLOW}[1/5] Pulling latest code from origin...${NC}"
cd "$SCRIPT_DIR"
git fetch origin
git pull origin main || git pull origin master || echo "Warning: Could not pull, using local code"

# Step 2: Get version
echo -e "${YELLOW}[2/5] Determining build version...${NC}"
BUILD_VERSION=$(git describe --tags --always 2>/dev/null || echo "dev-$(date +%s)")
echo "Build version: $BUILD_VERSION"

# Step 2.5: Prepare Canifa icon
echo -e "${YELLOW}[2.5/5] Preparing Canifa icon...${NC}"
mkdir -p "$SCRIPT_DIR/public"
cp -f "/home/anhvh/app/outservice/public/image.png" "$SCRIPT_DIR/public/image.png" || echo "Warning: Could not copy icon"

# Step 3: Build image
echo -e "${YELLOW}[3/5] Building Docker image as ${APP_NAME}...${NC}"
FULL_IMAGE_NAME="${REGISTRY}${REGISTRY:+/}${APP_NAME}"
docker build \
  --build-arg APP_NAME="$APP_NAME" \
  --build-arg APP_ICON="$APP_ICON" \
  --build-arg BUILD_VERSION="$BUILD_VERSION" \
  -t "${FULL_IMAGE_NAME}:${IMAGE_TAG}" \
  -t "${FULL_IMAGE_NAME}:${BUILD_VERSION}" \
  -f "$SCRIPT_DIR/Dockerfile" \
  "$SCRIPT_DIR"

echo -e "${GREEN}✓ Image built: ${FULL_IMAGE_NAME}:${IMAGE_TAG}${NC}"

# Step 4: Push to registry (optional)
if [ -n "$REGISTRY" ]; then
  echo -e "${YELLOW}[4/5] Pushing image to registry: ${REGISTRY}...${NC}"
  docker push "${FULL_IMAGE_NAME}:${IMAGE_TAG}"
  docker push "${FULL_IMAGE_NAME}:${BUILD_VERSION}"
  echo -e "${GREEN}✓ Pushed to registry${NC}"
else
  echo -e "${YELLOW}[4/5] Skipping registry push (local build only)${NC}"
fi

# Step 5: Deploy locally with Docker Compose when available
if [ -f "$SCRIPT_DIR/docker-compose.yml" ]; then
  echo -e "${YELLOW}[5/5] Starting container with Docker Compose...${NC}"
  docker compose -f "$SCRIPT_DIR/docker-compose.yml" up -d --remove-orphans
  echo -e "${GREEN}✓ Container started with Docker Compose${NC}"
else
  echo -e "${YELLOW}[5/5] No docker-compose.yml found, skipping auto-start${NC}"
fi

# Step 6: Summary
echo -e "${YELLOW}[6/6] Build summary${NC}"
docker images | grep "$APP_NAME" | head -3

echo ""
echo -e "${GREEN}=== Build Complete ===${NC}"
echo -e "Run locally with:"
echo -e "  ${BLUE}docker compose -f $SCRIPT_DIR/docker-compose.yml up -d${NC}"
echo ""
