#!/usr/bin/env bash
# Android APK security analyzer — extract metadata and check for common issues.
# Usage: bash scripts/apk_analyze.sh <app.apk>
set -euo pipefail

APK="${1:?Usage: $0 <app.apk>}"

if ! command -v aapt &>/dev/null && ! command -v apktool &>/dev/null; then
  echo "ERROR: aapt or apktool required"
  echo "  Install aapt: apt install aapt (or Android SDK build-tools)"
  echo "  Install apktool: https://ibotpeaches.github.io/Apktool/"
  exit 1
fi

echo "=== APK Analysis: $APK ==="
echo ""

if command -v aapt &>/dev/null; then
  echo "--- Package Info ---"
  aapt dump badging "$APK" 2>/dev/null | grep -E "package:|sdkVersion:|targetSdkVersion:|uses-permission:"

  echo ""
  echo "--- Permissions ---"
  aapt dump permissions "$APK" 2>/dev/null | while read -r line; do
    if echo "$line" | grep -qiE "INTERNET|READ_CONTACTS|ACCESS_FINE_LOCATION|CAMERA|READ_SMS|RECORD_AUDIO|READ_CALL_LOG"; then
      echo "  ⚠️  $line"
    else
      echo "  $line"
    fi
  done
fi

echo ""
echo "--- Certificate Info ---"
keytool -printcert -jarfile "$APK" 2>/dev/null | grep -E "Owner:|Issuer:|Valid from:" || echo "  Cannot read certificate"

echo ""
echo "--- Security Checks ---"
# Check for debuggable
if aapt dump xmltree "$APK" AndroidManifest.xml 2>/dev/null | grep -q "debuggable.*0x1"; then
  echo "  🔴 App is debuggable!"
else
  echo "  ✅ Not debuggable"
fi

# Check for backup allowed
if aapt dump xmltree "$APK" AndroidManifest.xml 2>/dev/null | grep -q "allowBackup.*0x1"; then
  echo "  ⚠️  Backup allowed (data extraction risk)"
else
  echo "  ✅ Backup not allowed"
fi

# Check for cleartext traffic
if aapt dump xmltree "$APK" AndroidManifest.xml 2>/dev/null | grep -q "usesCleartextTraffic.*0x1"; then
  echo "  🔴 Cleartext traffic enabled!"
else
  echo "  ✅ Cleartext traffic disabled"
fi
