#!/bin/bash
set -euo pipefail
flutter clean
flutter pub get
flutter build apk --release
cp build/app/outputs/flutter-apk/app-release.apk ./release/eggtimer.apk
echo "APK built and copied to ./release/eggtimer.apk"
GITEA_URL="https://git.ude-consult.de"
GITEA_TOKEN="6ea286299e8e081d9923d5deea2fbd91ad83dc8e"
OWNER="Arnold"
REPO="EggTimer"
APK_PATH="release/eggtimer.apk"

PUBSPEC="pubspec.yaml"

line=$(grep "^version:" $PUBSPEC | awk '{print $2}')
before_plus="${line%%+*}"     # 1.0.3
build="${line##*+}"

major=$(echo $before_plus | cut -d. -f1)
minor=$(echo $before_plus | cut -d. -f2)
patch=$(echo $before_plus | cut -d. -f3)

patch=$((patch + 1))
build=$((build + 1))

new="${major}.${minor}.${patch}+${build}"

echo "Neue Version: $new"

sed -i "s/^version: .*/version: ${new}/" "$PUBSPEC"

# Version z.B. aus Datei oder Argument
VERSION_TAG=$(grep "^version:" pubspec.yaml | awk '{print $2}')

RELEASE_TITLE="EggTimer ${VERSION_TAG}"
RELEASE_BODY="Automatisch erstelltes Release ${VERSION_TAG}."

# 1. Release anlegen
create_release_response=$(curl -sS -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: token ${GITEA_TOKEN}" \
  "${GITEA_URL}/api/v1/repos/${OWNER}/${REPO}/releases" \
  -d "{
    \"tag_name\": \"${VERSION_TAG}\",
    \"target\": \"main\",
    \"title\": \"${RELEASE_TITLE}\",
    \"note\": \"${RELEASE_BODY}\",
    \"draft\": false,
    \"prerelease\": false
  }")

release_id=$(echo "$create_release_response" | jq -r '.id')

if [[ "$release_id" == "null" || -z "$release_id" ]]; then
  echo "Fehler: Konnte Release-ID nicht auslesen."
  echo "$create_release_response"
  exit 1
fi

echo "Release ${VERSION_TAG} erstellt, ID=${release_id}"

# 2. APK hochladen
curl -sS -X POST \
  -H "Authorization: token ${GITEA_TOKEN}" \
  -F "attachment=@${APK_PATH};filename=eggtimer-${VERSION_TAG}.apk" \
  "${GITEA_URL}/api/v1/repos/${OWNER}/${REPO}/releases/${release_id}/assets"

echo "APK hochgeladen."


