pipeline {
   agent {
     label 'flutter'
   }
   options {
       disableConcurrentBuilds()
       buildDiscarder(logRotator(numToKeepStr: '10'))
   }
   parameters {
       string(name: 'APP_PACKAGE_ID', defaultValue: 'comptaplan.app', description: 'Application package id used as android identifier')
       string(name: 'APP_BUNDLE_ID', defaultValue: 'comptaplan_app', description: 'Application bundle id used as ios identifier')
       string(name: 'APP_TITLE', defaultValue: 'My Comptaplan', description: 'Application title')
       string(name: 'APP_URI', defaultValue: 'https://my.comptaplan.be', description: 'Application uri')
       string(name: 'APP_COLOR', defaultValue: 'blue', description: 'Application color (blue, teal, ...)')
       string(name: 'BUILD_MODE', defaultValue: 'debug', description: 'Flutter build mode (debug/release)')
       string(name: 'ANDROID_SIGNING_KEYSTORE_CREDENTIAL', defaultValue: 'jenkins-gestemps-android-service-secret-keystore')
       string(name: 'ANDROID_SIGNING_KEYSTORE_PASSWORD_CREDENTIAL', defaultValue: 'jenkins-gestemps-android-service-secret-keystore-password')
       string(name: 'ANDROID_SIGNING_KEY_PASSWORD_CREDENTIAL', defaultValue: 'jenkins-gestemps-android-service-secret-key-password')
       string(name: 'ANDROID_SIGNING_KEY_ALIAS', defaultValue: 'comptaplan',
              description: 'The key alias to use within the keystore')
       booleanParam(name: 'SKIP_PUBLISH', defaultValue: 'true', description: 'Skip publishing apk')
       string(name: 'GIT_CREDENTIAL_ID', defaultValue: 'jenkins-jenkins-ssh-key', description: '')
       string(name: 'RELEASE_MESSAGE', defaultValue: 'Nouvelle version', description: 'A release message')
       string(name: 'ANDROID_UPLOAD_TRACK', defaultValue: 'alpha', description: 'Upload track')
       string(name: 'ANDROID_RELEASE_STATUS', defaultValue: 'completed', description: 'draft/completed')
       string(name: 'ANDROID_API_KEY_CREDENTIAL', defaultValue: 'jenkins-gestemps-android-service-secret-api-key', description: 'Api key to for the play store api')
       string(name: 'GIT_SSH_REMOTE_NAME', defaultValue: 'ssh://git@gitea.valuya.com:2022/Valuya/embedded_webview.git',
             description: 'We use ssh authentication, but gitea may use an http remotes by default. This is the remote to push the build number increment.')
       string(name: 'GIT_PUSH_BRANCH', defaultValue: 'android-releases', description: 'A branch to push the commit')
       string(name: 'GIT_TAG', defaultValue: '', description: 'An additional tag to push')
       string(name: 'SSH_KNOWN_HOSTS_FILE', defaultValue: '/var/run/ssh/known_hosts.gitea.valuya.com', description: 'Known hosts for ssh client (might be used to get flutter git dependencies and push commits)')
       booleanParam(name: 'SKIP_PUSH_TAG', defaultValue: 'true', description: 'Skip push tag')
       string(name: 'NODEJS_INSTALLATION', defaultValue: 'node 15',description: 'Nodejs installation to use')
   }
   stages {
       stage ('Build') {
           steps {
                 script {
                  env.APP_PACKAGE_ID= params.APP_PACKAGE_ID
                  env.APP_BUNDLE_ID= params.APP_BUNDLE_ID
                  env.APP_TITLE= params.APP_TITLE
                  env.APP_URI= params.APP_URI
                  env.APP_COLOR= params.APP_COLOR
                  env.BUILD_MODE= params.BUILD_MODE
                  env.SSH_KNOWN_HOSTS_FILE= params.SSH_KNOWN_HOSTS_FILE
                  env.ANDROID_KEY_ALIAS= params.ANDROID_SIGNING_KEY_ALIAS
                }
               container ('flutter') {
                  sshagent(["${params.GIT_CREDENTIAL_ID}"]) {
                      withCredentials([
                        file(credentialsId: params.ANDROID_SIGNING_KEYSTORE_CREDENTIAL, variable: 'ANDROID_KEYSTORE_FILE'),
                        string(credentialsId: params.ANDROID_SIGNING_KEYSTORE_PASSWORD_CREDENTIAL, variable: 'ANDROID_KEYSTORE_PASSWORD'),
                        string(credentialsId: params.ANDROID_SIGNING_KEY_PASSWORD_CREDENTIAL, variable: 'ANDROID_KEY_PASSWORD')
                      ]) {
                          sh 'flutter doctor'
                          sh 'GIT_SSH_COMMAND="ssh -o UserKnownHostsFile=$SSH_KNOWN_HOSTS_FILE" flutter pub get'
                          sh 'flutter clean'
                          sh './tools/set-bundle-identifier.sh "$APP_BUNDLE_ID"'
                          sh './tools/set-package.sh "$APP_PACKAGE_ID"'
                          sh './tools/set-title.sh "$APP_TITLE"'
                          sh './tools/jenkins-build-android.sh'
                          stash(name: 'outputs', includes: 'build/app/outputs/**')
                      }
                  }
               }
           }
       }
       stage ('Push') {
           when { anyOf {
               expression {return (params.SKIP_PUBLISH == false)}
               expression {return (env.GIT_BRANCH == "master" )}
           }}
           steps {
                script {
                  env.SKIP_PUSH_TAG= params.SKIP_PUSH_TAG
                  env.GIT_TAG= params.GIT_TAG
                  env.GIT_PUSH_BRANCH = params.GIT_PUSH_BRANCH
                  env.ANDROID_UPLOAD_TRACK = params.ANDROID_UPLOAD_TRACK
                  env.ANDROID_RELEASE_STATUS = params.ANDROID_RELEASE_STATUS
                  env.RELEASE_MESSAGE = params.RELEASE_MESSAGE
                  env.GIT_SSH_REMOTE_NAME = params.GIT_SSH_REMOTE_NAME
                  env.SSH_KNOWN_HOSTS_FILE = params.SSH_KNOWN_HOSTS_FILE
                }
                unstash(name: 'outputs')
                sshagent(["${params.GIT_CREDENTIAL_ID}"]) {
                  nodejs(nodeJSInstallationName: "${params.NODEJS_INSTALLATION}") {
                    withCredentials([
                        file(credentialsId: params.ANDROID_API_KEY_CREDENTIAL, variable: 'GOOGLE_APPLICATION_CREDENTIALS')
                    ]) {
                        sh './tools/jenkins-publish-android.sh'
                    }

                  }
                  sh '''
                       VERSION_CODE=$(./tools/jenkins-increment-buildnumber.sh || echo $?)
                       [ "$VERSION_CODE" == "0" ] && exit 1
                       git config user.email "jenkins@valuya.com"
                       git config user.name "Jenkins release"
                       git add pubspec.yaml
                       git remote add ssh "$GIT_SSH_REMOTE_NAME"
                       git commit -m "Bump to build $VERSION_CODE"
                       export GIT_SSH_COMMAND="ssh -o UserKnownHostsFile=$SSH_KNOWN_HOSTS_FILE"
                       git push ssh HEAD:$GIT_PUSH_BRANCH
                       if [ "$SKIP_PUSH_TAG" != "true" ] ; then
                         git tag "$GIT_TAG"
                         git push ssh "$GIT_TAG"
                       fi
                  '''
               }
           }
       }
   }

   post {
       failure {
         mail(
           to: 'charlyghislain@gmail.com',
           subject: "Release failed: $JOB_NAME ${params.GIT_REPO_BRANCH} ${BUILD_NUMBER}",
           body: "See job at ${BUILD_URL}"
         )
       }
   }
}


