#!/bin/bash

# =============================================================================
# Mergin Maps Mobile - Two-Stage Build Script (Podman)
# =============================================================================
# This script builds the Mergin Maps Mobile application using two separate
# images: a base environment image and a build image. This approach optimizes
# layer caching and makes images more reusable.
#
# Usage: ./build-two-stage.sh [OPTION]
# Options:
#   latest    - Build with 'latest' tag
#   version   - Build with version tag (requires VERSION env var)
#   date      - Build with date-based tag (YYYYMMDD-HHMM)
#   git       - Build with git commit hash tag
#   combined  - Build with version-date combination
#   help      - Show this help message
# =============================================================================

set -e # Exit on any error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Image names
BASE_IMAGE_NAME="mergin-maps-base"
BUILD_IMAGE_NAME="mergin-maps-build"

# Function to print colored output
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_step() {
    echo -e "${PURPLE}[STEP]${NC} $1"
}

print_build() {
    echo -e "${CYAN}[BUILD]${NC} $1"
}

# Function to show help
show_help() {
    echo "Mergin Maps Mobile - Two-Stage Build Script (Podman)"
    echo ""
    echo "Usage: $0 [OPTION]"
    echo ""
    echo "Options:"
    echo "  latest    Build with 'latest' tag"
    echo "  version   Build with version tag (requires VERSION env var)"
    echo "  date      Build with date-based tag (YYYYMMDD-HHMM)"
    echo "  git       Build with git commit hash tag"
    echo "  combined  Build with version-date combination"
    echo "  help      Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 latest"
    echo "  VERSION=1.0.0 $0 version"
    echo "  $0 date"
    echo "  $0 git"
    echo "  VERSION=1.0.0 $0 combined"
    echo ""
    echo "Environment Variables:"
    echo "  VERSION   Version number for version/combined builds (e.g., 1.0.0)"
    echo "  ARTIFACTORY_URL   Artifactory base URL (default: https://artifactory.company.com)"
    echo "  SDKMAN_API_URL    SDKMAN API URL (default: https://artifactory.company.com/sdkman/api/2)"
    echo ""
    echo "Build Process:"
    echo "  1. Build base environment image (mergin-maps-base)"
    echo "  2. Build application image using base image (mergin-maps-build)"
    echo "  3. Extract APK from build image"
    echo ""
    echo "The final APK will be available at:"
    echo "  /var/www/mergin-maps/build/app/android-build/build/outputs/apk/release/android-build-release.apk"
}

# Function to determine image tag
determine_tag() {
    local option=$1
    local tag=""
    
    case "$option" in
        "latest")
            tag="latest"
            ;;
        "version")
            if [ -z "$VERSION" ]; then
                print_error "VERSION environment variable is required for version build"
                print_info "Example: VERSION=1.0.0 $0 version"
                exit 1
            fi
            tag="$VERSION"
            ;;
        "date")
            tag=$(date +%Y%m%d-%H%M)
            ;;
        "git")
            if command -v git >/dev/null 2>&1; then
                tag="commit-$(git rev-parse --short HEAD)"
            else
                print_error "Git is not available. Cannot generate git-based tag."
                exit 1
            fi
            ;;
        "combined")
            if [ -z "$VERSION" ]; then
                print_error "VERSION environment variable is required for combined build"
                print_info "Example: VERSION=1.0.0 $0 combined"
                exit 1
            fi
            DATE_TAG=$(date +%Y%m%d)
            tag="${VERSION}-${DATE_TAG}"
            ;;
    esac
    
    echo "$tag"
}

# Function to build base image
build_base_image() {
    local tag=$1
    local build_args="--network=host"
    
    # Set default Artifactory URLs if not provided
    local artifactory_url="${ARTIFACTORY_URL:-https://artifactory.company.com}"
    local sdkman_api_url="${SDKMAN_API_URL:-${artifactory_url}/sdkman/api/2}"
    
    print_step "Building base environment image with all dependencies..."
    print_info "Image: ${BASE_IMAGE_NAME}:${tag}"
    print_info "Using Artifactory URL: ${artifactory_url}"
    print_info "Using SDKMAN API URL: ${sdkman_api_url}"
    
    if podman build \
        ${build_args} \
        --tag "${BASE_IMAGE_NAME}:${tag}" \
        --tag "${BASE_IMAGE_NAME}:latest" \
        --build-arg BUILD_DATE="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" \
        --build-arg VCS_REF="$(git rev-parse HEAD 2>/dev/null || echo 'unknown')" \
        --build-arg VERSION="${tag}" \
        --build-arg ANDROID_SDK_URL="${artifactory_url}/android-sdk" \
        --build-arg MERGIN_SDK_ARM_URL="${artifactory_url}/mergin-sdk/arm-android-20240517-224/mergin-maps-input-sdk-qt-6.6.3-arm-android-20240517-224.tar.gz" \
        --build-arg MERGIN_SDK_ARM64_URL="${artifactory_url}/mergin-sdk/arm64-android-20240517-224/mergin-maps-input-sdk-qt-6.6.3-arm64-android-20240517-224.tar.gz" \
        --build-arg SDKMAN_URL="${artifactory_url}/sdkman/get.sdkman.io" \
        --build-arg SDKMAN_API_URL="${sdkman_api_url}" \
        -f Dockerfile.base \
        .; then
        print_success "Base environment image built successfully: ${BASE_IMAGE_NAME}:${tag}"
    else
        print_error "Failed to build base environment image: ${BASE_IMAGE_NAME}:${tag}!"
        exit 1
    fi
}

# Function to build application image
build_application_image() {
    local tag=$1
    local build_args="--network=host"
    
    print_step "Building application image..."
    print_info "Image: ${BUILD_IMAGE_NAME}:${tag}"
    print_info "All dependencies are already available in the base image via shared volume"
    
    # Update the build Dockerfile to use the correct base image
    print_info "Updating build Dockerfile to use base image: ${BASE_IMAGE_NAME}:${tag}"
    sed -i "s|FROM mergin-maps-base:latest|FROM ${BASE_IMAGE_NAME}:${tag}|g" Dockerfile.build
    
    if podman build \
        ${build_args} \
        --tag "${BUILD_IMAGE_NAME}:${tag}" \
        --tag "${BUILD_IMAGE_NAME}:latest" \
        --build-arg BUILD_DATE="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" \
        --build-arg VCS_REF="$(git rev-parse HEAD 2>/dev/null || echo 'unknown')" \
        --build-arg VERSION="${tag}" \
        -f Dockerfile.build \
        .; then
        print_success "Application image built successfully: ${BUILD_IMAGE_NAME}:${tag}"
    else
        print_error "Failed to build application image: ${BUILD_IMAGE_NAME}:${tag}!"
        exit 1
    fi
}

# Function to extract APK
extract_apk() {
    local tag=$1
    
    print_step "Extracting APK from build image..."
    
    # Create output directory
    mkdir -p output
    
    # Extract APK from build container
    if podman run --rm \
        -v "$(pwd)/output:/output:Z" \
        "${BUILD_IMAGE_NAME}:${tag}" \
        sh -c "
          if [ -f '/var/www/mergin-maps/build/app/android-build/build/outputs/apk/release/android-build-release.apk' ]; then
            echo 'APK found, copying to output directory...'
            cp '/var/www/mergin-maps/build/app/android-build/build/outputs/apk/release/android-build-release.apk' '/output/mergin-maps-mobile.apk'
            ls -la '/output/mergin-maps-mobile.apk'
            echo 'APK size:' \$(du -h '/output/mergin-maps-mobile.apk' | cut -f1)
          else
            echo 'APK not found at expected location'
            echo 'Available files in build directory:'
            find /var/www/mergin-maps/build -name '*.apk' -type f 2>/dev/null || echo 'No APK files found'
            exit 1
          fi
        "; then
        print_success "APK extracted successfully to output/mergin-maps-mobile.apk"
        print_info "APK size: $(du -h output/mergin-maps-mobile.apk | cut -f1)"
    else
        print_error "Failed to extract APK from build image!"
        exit 1
    fi
}

# Main script logic
case "${1:-help}" in
    "latest"|"version"|"date"|"git"|"combined")
        # Determine the image tag
        TAG=$(determine_tag "$1")
        
        print_build "Starting two-stage build for Mergin Maps Mobile"
        print_info "Tag: ${TAG}"
        print_info "Base image: ${BASE_IMAGE_NAME}:${TAG}"
        print_info "Build image: ${BUILD_IMAGE_NAME}:${TAG}"
        
        # Build base environment image
        build_base_image "$TAG"
        
        # Build application image
        build_application_image "$TAG"
        
        # Extract APK
        extract_apk "$TAG"
        
        print_success "Two-stage build completed successfully!"
        print_info "Base image: ${BASE_IMAGE_NAME}:${TAG}"
        print_info "Build image: ${BUILD_IMAGE_NAME}:${TAG}"
        print_info "APK location: output/mergin-maps-mobile.apk"
        ;;
        
    "help"|*)
        show_help
        ;;
esac
