// droidwatchScan.groovy — Jenkins shared library function.
//
// Drop this file into the shared library of your Jenkins controller under
// `vars/droidwatchScan.groovy`, then call from any Jenkinsfile:
//
//     droidwatchScan(
//         apkPath: "app/build/outputs/apk/release/app-release.apk",
//         apiKey:  env.DROIDWATCH_API_KEY,
//         failOn:  "Malicious|High Risk",
//     )
//
// Sets the following environment variables for downstream steps:
//   env.DROIDWATCH_RUN_ID
//   env.DROIDWATCH_VERDICT
//   env.DROIDWATCH_SCORE
//   env.DROIDWATCH_REPORT_URL
//
// Fails the build (currentBuild.result = "FAILURE", non-zero exit) when the
// verdict matches `failOn`. The classic Jenkins error → red badge applies.

def call(Map cfg = [:]) {
    if (!cfg.apkPath)  { error "droidwatchScan: 'apkPath' is required" }
    if (!cfg.apiKey)   { error "droidwatchScan: 'apiKey' is required (mark it as a secret credential)" }

    def server      = cfg.server      ?: "https://droidwatch.app"
    def failOn      = cfg.failOn      ?: "Malicious"
    def timeout     = (cfg.timeout    ?: 600).toString()
    def pollSeconds = (cfg.pollEvery  ?: 10).toString()

    def envFile = "${pwd(tmp: true)}/droidwatch.env"

    withEnv([
        "DW_APK_PATH=${cfg.apkPath}",
        "DW_API_KEY=${cfg.apiKey}",
        "DW_SERVER=${server}",
        "DW_FAIL_ON=${failOn}",
        "DW_TIMEOUT=${timeout}",
        "DW_POLL_INTERVAL=${pollSeconds}",
        "DW_OUTPUT_FILE=${envFile}",
    ]) {
        sh """
            set -e
            for cmd in curl jq; do
              if ! command -v \$cmd >/dev/null 2>&1; then
                echo "ERROR: '\$cmd' missing on the Jenkins agent — install it (apt-get install \$cmd or brew install \$cmd)." >&2
                exit 4
              fi
            done
            tmprunner="\$(mktemp -t droidwatch-scan.XXXXXX.sh)"
            curl --fail --silent --show-error --location \\
                 -o "\$tmprunner" "${server}/ci/lib/droidwatch-scan.sh"
            chmod +x "\$tmprunner"
            bash "\$tmprunner"
            rc=\$?
            rm -f "\$tmprunner"
            exit \$rc
        """
    }

    // Re-export outputs as env vars so later stages can `env.DROIDWATCH_VERDICT` them.
    def lines = readFile(envFile).split("\n")
    lines.each { line ->
        if (line?.contains("=")) {
            def (k, v) = line.split("=", 2)
            env."DROIDWATCH_${k.toUpperCase()}" = v
        }
    }
    echo "Droidwatch verdict: ${env.DROIDWATCH_VERDICT} (score ${env.DROIDWATCH_SCORE}) — ${env.DROIDWATCH_REPORT_URL}"
}
