#!/bin/bash

# =============================================================================
# Mergin Maps Mobile - Build Script (Podman)
# =============================================================================
# This script builds the Mergin Maps Mobile application using Podman
# with external dependencies managed via Artifactory variables.
#
# Usage: ./build.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'
NC='\033[0m' # No Color

# Image name
IMAGE_NAME="mergin-maps"

# 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"
}

# Function to show help
show_help() {
    echo "Mergin Maps Mobile - 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 "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 build image
build_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_info "Building image ${IMAGE_NAME}:${tag} with Podman..."
    print_info "Using Artifactory URL: ${artifactory_url}"
    print_info "Using SDKMAN API URL: ${sdkman_api_url}"
    
    if podman build \
        ${build_args} \
        --tag "${IMAGE_NAME}:${tag}" \
        --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}" \
        .; then
        print_success "Successfully built ${IMAGE_NAME}:${tag}"
    else
        print_error "Failed to build ${IMAGE_NAME}:${tag}!"
        exit 1
    fi
}

# Main script logic
case "${1:-help}" in
    "latest"|"version"|"date"|"git"|"combined")
        # Determine the image tag
        TAG=""
        if [ "$1" = "latest" ]; then
            TAG="latest"
        elif [ "$1" = "version" ]; then
            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"
        elif [ "$1" = "date" ]; then
            TAG=$(date +%Y%m%d-%H%M)
        elif [ "$1" = "git" ]; then
            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
        elif [ "$1" = "combined" ]; then
            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}"
        fi

        print_info "Starting build for Mergin Maps Mobile with tag: ${TAG}"
        build_image "$TAG"
        
        print_info "You can now run the container to extract the APK:"
        print_info "  podman run --rm -v \$(pwd)/output:/output:Z ${IMAGE_NAME}:${TAG} cp /var/www/mergin-maps/build/app/android-build/build/outputs/apk/release/android-build-release.apk /output/"
        ;;

    "help"|*)
        show_help
        ;;
esac

print_success "Build process completed!"
