#!/bin/bash
CI_PATH="/Volumes/Copyparty/Zcode Cloud/StickerSlack/"
REPO_URL=https://github.com/neon443/StickerSlack
REPO_PATH="$PWD/StickerSlack/"
ARCHIVE_PATH="$REPO_URL/temp"
rm -rf "$ARCHIVE_PATH"
mkdir "$ARCHIVE_PATH"

if [[ -e "$REPO_PATH" ]]; then
	echo h
else
	git clone "$REPO_URL" "$REPO_PATH"
fi

cd "$REPO_PATH"
git pull

if [[ -z "$1" ]]; then
	echo "select a commit to build for; or `main`"
	exit 1
elif [[ "$1" == "main" ]]; then
	git switch main
else
	git checkout "$1"
fi

xcodebuild clean -project StickerSlack.xcodeproj -scheme StickerSlack \
-configuration Release

XCCONFIG_PATH="$PWD/Config.xcconfig"
VERSION=$(grep '^VERSION[[:space:]]*=' "$XCCONFIG_PATH" | cut -d= -f2 | xargs)
BUILD=$(grep '^BUILD[[:space:]]*=' "$XCCONFIG_PATH" | cut -d= -f2 | xargs)
VERSION="$VERSION ($BUILD) $1"

OUTPUT_PATH="$CI_PATH/$VERSION ($BUILD)"
mkdir -p "$OUTPUT_PATH"

xcodebuild -project StickerSlack.xcodeproj -scheme StickerSlack -archivePath "$ARCHIVE_PATH.xcarchive archive"
xcodebuild -exportArchive -archivePath "$ARCHIVE_PATH.xcarchive" -exportPath "$OUTPUT_PATH" -exportOptionsPlist "$CI_PATH/exportOptions.plist"