#!/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
}

NO_DEPLOY="nodeploy"
if [[ "$CI_COMMIT_MESSAGE" == *"$NO_DEPLOY"* ]]; then
  echo "🐝 No deploy required."
  exit 0
fi

#Passed external variables
FILES_PATH=$1
IPA_DEPLOY_TARGET=$2
IPA_PATH=$3
IPA_FILE=$4
PLATFORM=$5

#Several cases for uploading created ipa.
if [ "$IPA_DEPLOY_TARGET" == "TESTFLIGHT" ]; then
    #git log --pretty=format:'%h %s' -n $1 > $2

    unlock_login_keychain "$K8S_SECRET_SPOCK"

    #upload
    xcrun altool \
		--upload-app \
		--username "juraldinio@me.com" \
		--password "$K8S_SECRET_NOTARIZATION" \
		-t $PLATFORM \
		--file $IPA_PATH/$IPA_FILE
    
    if [ "$?" != "0" ]; then
        echo >&2 "⛔️ Error: upload build failed";
        exit 1
    fi

	sleep 1
	
	# Upload debug symbols to Crashlytics
	
	#CRASHLYTICS_PATH=$IPA_PATH/Crashlytics
	#$CRASHLYTICS_PATH/upload-symbols -gsp $CRASHLYTICS_PATH/GoogleService-Info.plist -p ios $CRASHLYTICS_PATH/dSYMs
	
	#if [ "$?" != "0" ]; then
	#    echo >&2 "Error ⛔️ upload crashlytics debug symbols";
	#    exit 1
	#fi
	
else
    echo "Nothing to do"
    exit 1
fi
