{ pkgs, lib, ... }: { # provisioning script builder provision = { name, serial ? null, disable ? [], uninstall ? [], install ? [], # list of { name, src } files ? {} # src -> dest mapping }: let adb = "${pkgs.android-tools}/bin/adb"; # Helper to generate disable commands disableCmds = lib.concatMapStringsSep "\n" (pkg: '' echo " - Disabling ${pkg}..." ${adb} ${if serial != null then "-s ${serial}" else ""} shell pm disable-user --user 0 ${pkg} || echo " (Keep going, might be already disabled)" '') disable; # Helper to generate uninstall commands uninstallCmds = lib.concatMapStringsSep "\n" (pkg: '' echo " - Uninstalling ${pkg}..." ${adb} ${if serial != null then "-s ${serial}" else ""} shell pm uninstall -k --user 0 ${pkg} || echo " (Keep going, might be already uninstalled)" '') uninstall; # Helper to generate install commands installCmds = lib.concatMapStringsSep "\n" (app: '' echo " - Installing ${app.name}..." ${adb} ${if serial != null then "-s ${serial}" else ""} install -r "${app.src}" '') install; # Helper to generate push commands pushCmds = lib.concatStringsSep "\n" (lib.mapAttrsToList (src: dest: '' echo " - Pushing ${baseNameOf src} to ${dest}..." ${adb} ${if serial != null then "-s ${serial}" else ""} push "${src}" "${dest}" '') files); in pkgs.writeShellScriptBin "provision-${name}" '' set -euo pipefail echo "📱 Provisioning Android Device: ${name} ${if serial != null then "(${serial})" else ""}" # Check for ADB if ! command -v ${adb} &> /dev/null; then echo "Error: adb not found. This should not happen if built with nix." exit 1 fi # Check device connection echo " - Checking for device..." ${if serial != null then '' if ! ${adb} devices | grep -q "${serial}"; then echo "Error: Device ${serial} not found or not authorized." echo "Please connect the device and authorize USB debugging." exit 1 fi '' else '' DEVICE_COUNT=$(${adb} devices | grep -v "List" | grep "device$" | wc -l) if [ "$DEVICE_COUNT" -eq 0 ]; then echo "Error: No devices found." echo "Please connect a device and authorize USB debugging." exit 1 elif [ "$DEVICE_COUNT" -gt 1 ]; then echo "Error: Multiple devices found but no serial specified." ${adb} devices exit 1 fi ''} echo "✅ Device connected." echo "📦 Managing Packages (Debloat)..." ${disableCmds} ${uninstallCmds} echo "📥 Installing Applications..." ${installCmds} echo "📂 Syncing Files..." ${pushCmds} echo "🎉 Provisioning Complete for ${name}!" ''; }