plugins {
    id 'com.android.application'
}

def apiBaseUrl = project.findProperty('API_BASE_URL') ?: 'https://rdfz.yyangpt.cn'
def menuUrl = project.findProperty('MENU_URL') ?: ''
def maintenancePin = project.findProperty('MAINTENANCE_PIN') ?: ''
def escapedApiBaseUrl = apiBaseUrl.replace('\\', '\\\\').replace('"', '\\"').replaceAll('/+$', '')
def escapedMenuUrl = menuUrl.replace('\\', '\\\\').replace('"', '\\"')
def escapedMaintenancePin = maintenancePin.replace('\\', '\\\\').replace('"', '\\"')
def releaseStoreFilePath = System.getenv('ANDROID_RELEASE_STORE_FILE')
def releaseStorePassword = System.getenv('ANDROID_RELEASE_STORE_PASSWORD')
def releaseKeyAlias = System.getenv('ANDROID_RELEASE_KEY_ALIAS')
def releaseKeyPassword = System.getenv('ANDROID_RELEASE_KEY_PASSWORD')
def releaseSigningValues = [
        releaseStoreFilePath,
        releaseStorePassword,
        releaseKeyAlias,
        releaseKeyPassword
]
def releaseSigningConfigured = releaseSigningValues.every { it != null && !it.trim().isEmpty() }
def releaseSigningPartiallyConfigured = releaseSigningValues.any { it != null && !it.trim().isEmpty() }

if (releaseSigningPartiallyConfigured && !releaseSigningConfigured) {
    throw new GradleException('正式签名环境变量必须全部配置，禁止生成签名状态不明确的 Release 包。')
}
if (releaseSigningConfigured && !file(releaseStoreFilePath).isFile()) {
    throw new GradleException("正式签名文件不存在：${releaseStoreFilePath}")
}

android {
    namespace 'com.cpt.electronicmenu.tv'
    compileSdk 31

    defaultConfig {
        applicationId 'com.cpt.electronicmenu.tv'
        minSdk 23
        targetSdk 31
        versionCode 14
        versionName '1.3.10'

        buildConfigField 'String', 'API_BASE_URL', "\"${escapedApiBaseUrl}\""
        buildConfigField 'String', 'MENU_URL', "\"${escapedMenuUrl}\""
        buildConfigField 'String', 'MAINTENANCE_PIN', "\"${escapedMaintenancePin}\""
    }

    signingConfigs {
        release {
            if (releaseSigningConfigured) {
                storeFile file(releaseStoreFilePath)
                storePassword releaseStorePassword
                keyAlias releaseKeyAlias
                keyPassword releaseKeyPassword
            }
        }
    }

    buildTypes {
        debug {
            applicationIdSuffix '.debug'
            versionNameSuffix '-debug'
        }
        release {
            if (releaseSigningConfigured) {
                signingConfig signingConfigs.release
            }
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    lintOptions {
        abortOnError true
        checkReleaseBuilds false
    }
}
