android {
    signingConfigs {
        debug {
            storeFile file('signing/debug.jks')
        }
        upload {
            storeFile file('signing/upload.jks')
            storePassword System.env.UPLOAD_KEYSTORE_PWD ?: ''
            keyAlias 'upload'
            keyPassword System.env.UPLOAD_KEYSTORE_PWD ?: ''
        }
    }

    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            signingConfig signingConfigs.upload
        }
    }
}

play {
    serviceAccountCredentials.set(file('signing/play_account.json'))
    track.set('alpha')
}

project.afterEvaluate {
    // Setting up 'publishSample' task
    // Note, that in order to work this task requires ENCRYPT_KEY and UPLOAD_KEYSTORE_PWD env vars

    final publish = 'publishSample'

    project.task publish
    project.tasks[publish].dependsOn 'decryptUploadKeystore'
    project.tasks[publish].dependsOn 'decryptPlayAccount'
    project.tasks[publish].dependsOn 'publishReleaseBundle'
    project.tasks[publish].finalizedBy 'cleanUploadKeystore'
    project.tasks[publish].finalizedBy 'cleanPlayAccount'
}

task decryptUploadKeystore {
    doFirst {
        println 'Decrypt upload keystore'
        decode('upload.jks')
    }
}

task cleanUploadKeystore {
    doLast {
        println 'Clean up upload keystore'
        cleanup('upload.jks')
    }
}

task decryptPlayAccount {
    doFirst {
        println 'Decrypt Play account'
        decode('play_account.json')
    }
}

task cleanPlayAccount {
    doLast {
        println 'Clean up Play account'
        cleanup('play_account.json')
    }
}

private static void decode(String file) {
    def command = "openssl enc -aes-256-cbc -d -md sha512 -pbkdf2 -iter 100000 -salt" +
            " -in sample/signing/${file}.enc -out sample/signing/$file -k $System.env.ENCRYPT_KEY"
    def process = command.execute()
    def error = process.err.text
    if (error != null && !error.isEmpty()) {
        println "Error:\n" + error
        throw new RuntimeException("Error deconding $file",)
    }
}

private static void cleanup(String file) {
    "rm sample/signing/$file".execute()
}
