/*
 * Jenkins pipeline for natinfo_flutter
 * - dev branch: build unsigned APKs (no NDK install, no upload)
 * - v*  tag  : install NDK, build signed APKs, rename, upload
 */

pipeline {
    agent { label 'android-x86' }

    environment {
        FLUTTER_ROOT = "${HOME}/flutter"
        PATH = "${env.PATH}:${FLUTTER_ROOT}/bin:${HOME}/.pub-cache/bin:" +
               "${ANDROID_HOME}/platform-tools:" +
               "${ANDROID_HOME}/cmdline-tools/latest/bin"
        ANDROID_HOME     = "/home/jenkins/android-sdk"
        ANDROID_SDK_ROOT = "/home/jenkins/android-sdk"
    }

    stages {

        /*────────────────────────────────────────────────────────────*/
        stage('Install Flutter & Activate FVM') {
            steps {
                sh '''
                  set -eux

                  # 1) Clone Flutter stable if not already present
                  if [ ! -d "$FLUTTER_ROOT" ]; then
                    echo "Cloning Flutter stable into $FLUTTER_ROOT"
                    git clone https://github.com/flutter/flutter.git -b stable --depth 1 "$FLUTTER_ROOT"
                  else
                    echo "Flutter already exists at $FLUTTER_ROOT"
                  fi

                  # 2) Add Flutter to PATH for this shell
                  export PATH="$FLUTTER_ROOT/bin:$PATH"

                  # 3) Ensure Flutter toolchains are installed
                  flutter doctor -v

                  # 4) Activate FVM globally (puts fvm in ~/.pub-cache/bin)
                  flutter pub global activate fvm
                '''
            }
        }

        /*────────────────────────────────────────────────────────────*/
        stage('Clean workspace & caches') {
            steps {
                // Wipe out any previous workspace files
                deleteDir()
            }
        }

        /*────────────────────────────────────────────────────────────*/
        stage('Checkout code') {
            steps {
                // Fresh checkout of the repository
                checkout scm
            }
        }

        /*────────────────────────────────────────────────────────────*/
        stage('Ensure Android SDK & NDK') {
            steps {
                sh '''
                  set -eux

                  /opt/android/cmdline-tools/latest/bin/sdkmanager \
                    --sdk_root="$ANDROID_HOME" \
                    "platform-tools" \
                    "platforms;android-34" \
                    "build-tools;34.0.0" \
                    "ndk;27.0.12077973"

                  yes | /opt/android/cmdline-tools/latest/bin/sdkmanager \
                    --sdk_root="$ANDROID_HOME" --licenses
                '''
            }
        }

        /*────────────────────────────────────────────────────────────*/
        stage('Prepare signing material') {
            steps {
                withCredentials([
                    file  (credentialsId: 'natinfo-keystore', variable: 'KS'),
                    string(credentialsId: 'natinfo-ks-pass',  variable: 'KS_PASS'),
                    string(credentialsId: 'natinfo-key-pass', variable: 'KEY_PASS'),
                    string(credentialsId: 'natinfo-alias',    variable: 'ALIAS')
                ]) {
                    sh '''
                      set -eux

                      mkdir -p android/app
                      cp -f "$KS" android/app/release.jks

                      cat > android/key.properties <<EOF
storeFile=release.jks
storePassword=$KS_PASS
keyAlias=$ALIAS
keyPassword=$KEY_PASS
EOF
                    '''
                }
            }
        }

        /*────────────────────────────────────────────────────────────*/
        stage('Flutter pub get') {
            steps {
                sh '''
                  set -eux

                  # 1) Clean previous Flutter build artifacts
                  fvm flutter clean

                  # 2) Purge only the geolocator_android plugin so it will re-download
                  rm -rf "$HOME/.pub-cache/hosted/pub.dev/geolocator_android-"*

                  # 3) Fetch all dependencies
                  fvm flutter pub get
                '''
            }
        }

        /*────────────────────────────────────────────────────────────*/
        stage('Patch geolocator_android') {
            steps {
                sh '''
                    set -eux

                    # Navigate to the pub-cache directory and locate the plugin folder.
                    cd "${HOME}/.pub-cache/hosted/pub.dev"
                    plugin=$(ls -d geolocator_android-* | head -n 1)
                    if [ -z "$plugin" ]; then
                        echo "ERROR: geolocator_android plugin not found"
                        exit 1
                    fi
                    cd "$plugin"

                    ############################################################################
                    # APPLYING PATCH                                                           #
                    ############################################################################

                    # 2.1 Remove the GMS dependency from build.gradle.
                    sed -i "/play-services-location/d" android/build.gradle

                    # 2.2 Remove the FusedLocationClient.java file.
                    rm -f android/src/main/java/com/baseflow/geolocator/location/FusedLocationClient.java

                    # 2.3 Modify GeolocationManager.java:
                    GEO="android/src/main/java/com/baseflow/geolocator/location/GeolocationManager.java"

                    # a) Remove Google Play Services imports and associated classes.
                    sed -i "/com\\.google\\.android\\.gms/d" "$GEO"
                    sed -i "/ConnectionResult/d" "$GEO"
                    sed -i "/GoogleApiAvailability/d" "$GEO"

                    # b) Remove the createLocationClient method block.
                    sed -i "/public LocationClient createLocationClient/,/^  }/d" "$GEO"

                    # c) Remove the isGooglePlayServicesAvailable method block.
                    sed -i "/private boolean isGooglePlayServicesAvailable/,/^  }/d" "$GEO"

                    # d) Insert a new createLocationClient method after the class declaration.
                    sed -i "/implements .*ActivityResultListener {/a\\
            public LocationClient createLocationClient(\\
                Context context,\\
                boolean forceAndroidLocationManager,\\
                @Nullable LocationOptions locationOptions) {\\
            return new LocationManagerClient(context, locationOptions);\\
            }\\
        " "$GEO"
                '''
            }
        }
        
        /*────────────────────────────────────────────────────────────*/
        stage('Assemble split APKs') {
            steps {
                sh 'fvm flutter build apk --release --split-per-abi --verbose'
            }
        }

        /*────────────────────────────────────────────────────────────*/
        stage('Rename APKs') {
            steps {
                script {
                    def pub = readYaml file: 'pubspec.yaml'
                    if (!pub.version) error "No 'version:' in pubspec.yaml"
                    def version = pub.version.tokenize('+')[0]

                    sh """
                      cd build/app/outputs/flutter-apk
                      for f in *-release.apk; do
                        abi=\$(echo \$f | cut -d'-' -f2)
                        mv "\$f" "net.retiolus.natinfo-\${abi}-v${version}.apk"
                      done
                    """
                }
            }
        }

        /*────────────────────────────────────────────────────────────*/
        stage('Publish back to Codeberg') {
            steps {
                archiveArtifacts artifacts: 'build/app/outputs/flutter-apk/net.retiolus.natinfo-*-v*.apk',
                                 fingerprint: true
                publishGiteaAssets assets: 'build/app/outputs/flutter-apk/net.retiolus.natinfo-*-v*.apk'
            }
        }
    }
}
