#!/usr/bin/env bash

unlock_login_keychain() {
    if [ -z "$1" ]; then
        echo "Password parameter must be exists"
        return 1
    fi
    local timeout=3600
    if [ -n "$2" ]; then
        timeout=$2
    fi

    security list-keychains -s ~/Library/Keychains/login.keychain-db
    security unlock-keychain -p $1 ~/Library/Keychains/login.keychain-db
    security set-keychain-settings -t $timeout -l ~/Library/Keychains/login.keychain-db
}


#Passed external variables

ROOT=$(pwd)
CURRENT=$(basename "$ROOT")

MAIN_PATH=$1
DESTINATION=$2

#Remove Delivered data
rm -rf ~/Library/Developer/Xcode/DerivedData

cd $MAIN_PATH

cd example

# just test build on simulator
if [ "$DESTINATION" != "device" ]; then
	
	flutter build ios --simulator
	
	if [ "$?" != "0" ]; then
		echo >&2 "🚫 Error: Build ios example";
		exit 1
	fi
	
	flutter build apk --debug
	
	if [ "$?" != "0" ]; then
		echo >&2 "🚫 Error: Build android example";
		exit 1
	fi
	
	exit 0
fi

# Whole build to device

# Android

#flutter build appbundle --no-shrink

if [ "$?" != "0" ]; then
	echo >&2 "🚫 Error: Build android example";
	exit 1
fi

flutter build apk --no-shrink --build-number=$CI_PIPELINE_IID

if [ "$?" != "0" ]; then
	echo >&2 "🚫 Error: Build android example";
	exit 1
fi


# iOS

unlock_login_keychain "$K8S_SECRET_SPOCK"

#Sync versions and change build number for upload to TestFlight
BUNDLE_SHORT_VERSION=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "./ios/Runner/Info.plist")
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $CI_PIPELINE_IID" ./ios/Runner/Info.plist

flutter build ipa \
	--release \
	--export-options-plist=$ROOT/toolchain/NutPlayer-iOS-ExportOptions.plist

if [ "$?" != "0" ]; then
	echo >&2 "🚫 Error: Build ios example";
	exit 1
fi

cd $ROOT

# Create artifacts directory
mkdir Result

#cp build/app/outputs/bundle/release/app-release.aab Result
cp $MAIN_PATH/example/build/app/outputs/flutter-apk/app-release.apk Result
cp $MAIN_PATH/example/build/ios/ipa/NutPlayerFlutter.ipa Result
