#!/usr/bin/env bash
# set -e
# Define the build environment variable
# Get the version number from the pubspec.yaml file
BUILD_NUM=$(grep "version:" pubspec.yaml | awk '{print $2}' | awk -F'[:+]' '{print $2}')
BUILD_NAME=$(grep "version:" pubspec.yaml | awk '{print $2}' | awk -F'[:+]' '{print $1}')
echo "BUILD_NUM  :$BUILD_NUM"
echo "BUILD_NAME :$BUILD_NAME"

VERSION=$(grep "version:" pubspec.yaml | awk '{print $2}')
VERSION_NAME=$(grep "version:" pubspec.yaml | awk '{print $2}' | cut -d '+' -f 1)
# Get the project name from the pubspec.yaml file
PROJECT_NAME=$(grep "name:" pubspec.yaml | awk '{print $2}')

CURRENT_DATE_TIME=$(date +"%Y-%m-%d_%H-%M-%S")

BUILD_ENV=$1

PROJECT_BUILD_ENV="--debug"

SAVE_DIR="debug"


project_dir=$PWD

# Define the obfuscation settings based on the build environment
case $1 in
  debug)
    OBFUSCATION_SETTINGS=""
    ;;
  profile)
    OBFUSCATION_SETTINGS=""
    PROJECT_BUILD_ENV="--profile"
    SAVE_DIR="profile"
    ;;
  release)
    PROJECT_BUILD_ENV="--release"
    OBFUSCATION_SETTINGS="--obfuscate --split-debug-info=${project_dir}/buildPackage/$1"
    SAVE_DIR="release"
    ;;
  *)
    echo "Invalid build environment: $1"
    exit 1
    ;;
esac

# Define the obfuscation settings based on the build dart-define
#case $2 in
#  dev|sit|uat|prod)
#    ;;
#  *)
#    echo "Invalid build environment: $2"
#    exit 1
#    ;;
#esac

echo "Welcome"
echo "Version: $VERSION"
echo "Project Name: $PROJECT_NAME"
echo "Build Environment: $1"
#echo "Build Dart Define: $2"
echo "Project Directory: $project_dir"

 rm -r "${project_dir}"/buildPackage/$1 && echo "以前目录删除成功"
# Check if the buildPackage/$2 directory exists, and create it if it doesn't
if [ ! -d "${project_dir}/buildPackage/$1" ]; then
  mkdir -p "${project_dir}/buildPackage/$1"
fi

#sed 's/openProxyMan = true/openProxyMan = false/g' ./lib/core/http/common_http_manager.dart > tmp_file && mv tmp_file ./lib/core/http/common_http_manager.dart  && echo "修改成功"

echo "Build Command Line ："
echo "      flutter build apk $PROJECT_BUILD_ENV  $OBFUSCATION_SETTINGS --build-name=v${BUILD_NAME}-$CURRENT_DATE_TIME"
# Build the Android package with the specified obfuscation settings and current date and time in the file name
flutter build apk $PROJECT_BUILD_ENV   $OBFUSCATION_SETTINGS --build-name=$BUILD_NAME  --build-number=$BUILD_NUM



# Copy the generated Android package to the buildPackage directory
cp $project_dir/build/app/outputs/apk/$1/sunda-$BUILD_NAME.apk $project_dir/buildPackage/$1
mv $project_dir/buildPackage/$1/sunda-$BUILD_NAME.apk $project_dir/buildPackage/$1/sunda-spms-$BUILD_NAME-$CURRENT_DATE_TIME.apk

echo "Build completed successfully"
echo "Build package location: ${project_dir}/buildPackage/$1/sunda-v${VERSION}-$CURRENT_DATE_TIME-$PROJECT_BUILD_ENV.apk"