apply plugin: 'com.android.library'
apply from: '../shared/keepUnitySymbols.gradle'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'androidx.core:core:1.9.0'
    implementation 'androidx.games:games-activity:3.0.5'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
}

android {
    namespace "com.unity3d.player"
    // ndkPath "/Applications/Unity/Hub/Editor/6000.0.32f1/PlaybackEngines/AndroidPlayer/NDK"
    // ndkVersion "23.1.7779620"
    compileSdk 35
    buildToolsVersion = "34.0.0"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }

    defaultConfig {
        consumerProguardFiles "proguard-unity.txt"
        versionName "0.1.0"
        minSdk 23
        targetSdk 35
        versionCode 1

        ndk {
            abiFilters "arm64-v8a"
            debugSymbolLevel "none"
        }

        externalNativeBuild {
            cmake {
                arguments "-DANDROID_STL=c++_shared"
            }
        }
    }

    lint {
        abortOnError false
    }

    androidResources {
        ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:!CVS:!thumbs.db:!picasa.ini:!*~"
        noCompress = ['.unity3d', '.ress', '.resource', '.obb', '.bundle', '.unityexp'] + unityStreamingAssets.tokenize(', ')
    }

    packaging {
        jniLibs {
            useLegacyPackaging true
        }
    }
}


def getSdkDir() {
    Properties local = new Properties()
    local.load(new FileInputStream("${rootDir}/local.properties"))
    return local.getProperty('sdk.dir')
}

def GetIl2CppOutputPath(String workingDir, String abi) {
    return "${workingDir}/src/main/jniLibs/${abi}/libil2cpp.so";
}

def GetIl2CppSymbolPath(String workingDir, String abi) {
    return "${workingDir}/symbols/${abi}/libil2cpp.so";
}

def BuildIl2CppImpl(String workingDir, String configuration, String architecture, String abi, String[] staticLibraries) {
    def commandLineArgs = []
    commandLineArgs.add("--compile-cpp")
    commandLineArgs.add("--platform=Android")
    commandLineArgs.add("--architecture=${architecture}")
    commandLineArgs.add("--outputpath=${workingDir}/src/main/jniLibs/${abi}/libil2cpp.so")
    commandLineArgs.add("--baselib-directory=${workingDir}/src/main/jniStaticLibs/${abi}")
    commandLineArgs.add("--incremental-g-c-time-slice=3")
    commandLineArgs.add("--configuration=${configuration}")
    commandLineArgs.add("--dotnetprofile=unityaot-linux")
    commandLineArgs.add("--usymtool-path=${workingDir}/src/main/Il2CppOutputProject/usymtool")
    commandLineArgs.add("--profiler-report")
    commandLineArgs.add("--profiler-output-file=${workingDir}/build/il2cpp_${abi}_${configuration}/il2cpp_conv.traceevents")
    commandLineArgs.add("--print-command-line")
    commandLineArgs.add("--static-lib-il2-cpp")
    commandLineArgs.add("--data-folder=${workingDir}/src/main/Il2CppOutputProject/Source/il2cppOutput/data")
    commandLineArgs.add("--generatedcppdir=${workingDir}/src/main/Il2CppOutputProject/Source/il2cppOutput")
    commandLineArgs.add("--cachedirectory=${workingDir}/build/il2cpp_${abi}_${configuration}/il2cpp_cache")
    commandLineArgs.add("--tool-chain-path=${android.ndkDirectory}")

    staticLibraries.eachWithIndex {fileName, i->
        commandLineArgs.add("--additional-libraries=${workingDir}/src/main/jniStaticLibs/${abi}/${fileName}")
    }

    def executableExtension = ""
    if (org.gradle.internal.os.OperatingSystem.current().isWindows()) {
        executableExtension = ".exe"
        commandLineArgs = commandLineArgs*.replace('\"', '\\\"')
    }
    exec {
        executable "${workingDir}/src/main/Il2CppOutputProject/IL2CPP/build/deploy/il2cpp${executableExtension}"
        args commandLineArgs
        environment "ANDROID_SDK_ROOT", getSdkDir()
    }

    def dbgLevel =  project.android.defaultConfig.ndk.debugSymbolLevel;
    def usePublicSymbols = dbgLevel == null || !dbgLevel.toString().toLowerCase().equals("full")
    def extensionToRemove = usePublicSymbols ? ".dbg.so" : ".sym.so"
    def extensionToKeep = usePublicSymbols ? ".sym.so" : ".dbg.so"

    delete "${workingDir}/src/main/jniLibs/${abi}/libil2cpp${extensionToRemove}"
    ant.move(file: "${workingDir}/src/main/jniLibs/${abi}/libil2cpp${extensionToKeep}", tofile: "${workingDir}/symbols/${abi}/libil2cpp.so")

}

android {
    tasks.register('buildIl2Cpp') {
        def workingDir = projectDir.toString().replaceAll('\\\\', '/');
        def archs = [
            'arm64' : 'arm64-v8a'
        ]
        def staticLibs = [
            'arm64' : [  ]
        ]
        inputs.files fileTree(dir: 'src/main/Il2CppOutputProject', include: ['**/*'])
        inputs.files fileTree(dir: 'src/main/jniStaticLibs', include: ['**/*'])
        archs.each { arch, abi ->
            outputs.file GetIl2CppOutputPath(workingDir, abi)
            outputs.file GetIl2CppSymbolPath(workingDir, abi)
        }
        doLast {
            archs.each { arch, abi ->
                BuildIl2CppImpl(workingDir, 'Release', arch, abi, staticLibs[arch] as String[]);
            }
        }
    }

    afterEvaluate {
        if (project(':unityLibrary').tasks.findByName('mergeDebugJniLibFolders'))
            project(':unityLibrary').mergeDebugJniLibFolders.dependsOn buildIl2Cpp
        if (project(':unityLibrary').tasks.findByName('mergeReleaseJniLibFolders'))
            project(':unityLibrary').mergeReleaseJniLibFolders.dependsOn buildIl2Cpp
    }
    sourceSets {
        main {
            jni.srcDirs = ["src/main/Il2CppOutputProject"]
        }
    }
}

android.externalNativeBuild {
    cmake {
        version "3.22.1"
        path "src/main/cpp/CMakeLists.txt"
    }
}
android.buildFeatures {
    prefab true
}