#!/usr/bin/env bash

# ============================================================
# Android Management Tool
# Version 2.0
#
# Comprehensive Android device management via ADB
# ============================================================

set -u

VERSION="2.0"

# ------------------------------------------------------------
# Color definitions
# ------------------------------------------------------------

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
RESET='\033[0m'

# ------------------------------------------------------------
# Icon definitions
# ------------------------------------------------------------

INFO_ICON="ℹ️"
CHECK_ICON="✅"
WARNING_ICON="⚠️"
ERROR_ICON="❌"

# ------------------------------------------------------------
# Sensitive permissions
# ------------------------------------------------------------

SENSITIVE_PERMISSIONS=(

    "READ_CONTACTS"
    "WRITE_CONTACTS"

    "READ_CALL_LOG"
    "WRITE_CALL_LOG"

    "READ_SMS"
    "SEND_SMS"
    "RECEIVE_SMS"

    "READ_PHONE_STATE"
    "CALL_PHONE"

    "READ_LOCATION"
    "ACCESS_FINE_LOCATION"
    "ACCESS_COARSE_LOCATION"
    "ACCESS_BACKGROUND_LOCATION"

    "CAMERA"
    "RECORD_AUDIO"

    "WRITE_EXTERNAL_STORAGE"
    "READ_EXTERNAL_STORAGE"

    "READ_MEDIA_IMAGES"
    "READ_MEDIA_VIDEO"
    "READ_MEDIA_AUDIO"

    "POST_NOTIFICATIONS"

    "BODY_SENSORS"
    "ACTIVITY_RECOGNITION"

    "BLUETOOTH_SCAN"
    "BLUETOOTH_CONNECT"
    "NEARBY_WIFI_DEVICES"

    "USE_SIP"
    "PROCESS_OUTGOING_CALLS"

    "MANAGE_EXTERNAL_STORAGE"
    "SYSTEM_ALERT_WINDOW"
    "WRITE_SETTINGS"

    "PACKAGE_USAGE_STATS"

    "BIND_DEVICE_ADMIN"
    "BIND_ACCESSIBILITY_SERVICE"
    "BIND_NOTIFICATION_LISTENER_SERVICE"

    "QUERY_ALL_PACKAGES"
    "REQUEST_INSTALL_PACKAGES"

    "INSTALL_PACKAGES"
    "DELETE_PACKAGES"

    "MANAGE_DEVICE_POLICY_LOCK"

    "SET_TIME_ZONE"

    "MASTER_CLEAR"
)

# ------------------------------------------------------------
# ADB check
# ------------------------------------------------------------

check_adb() {

    if ! command -v adb >/dev/null 2>&1; then

        echo -e "${RED}${ERROR_ICON} adb is not installed.${RESET}"
        echo
        echo "Install Android platform tools:"
        echo
        echo "  openSUSE:"
        echo "    sudo zypper install android-tools"
        echo
        echo "  Fedora:"
        echo "    sudo dnf install android-tools"
        echo

        return 1
    fi

    return 0
}

# ------------------------------------------------------------
# Device check
# ------------------------------------------------------------

check_device() {

    if ! check_adb; then
        return 1
    fi

    if ! adb get-state >/dev/null 2>&1; then

        echo -e "${RED}${ERROR_ICON} No Android device detected.${RESET}"
        echo
        echo "Make sure:"
        echo "  1. USB debugging is enabled."
        echo "  2. The device is connected."
        echo "  3. USB debugging authorization was accepted."
        echo

        return 1
    fi

    return 0
}

# ------------------------------------------------------------
# Header
# ------------------------------------------------------------

print_header() {

    echo
    echo -e "${BLUE}============================================================${RESET}"
    echo -e "${BLUE}$1${RESET}"
    echo -e "${BLUE}============================================================${RESET}"
    echo
}

# ------------------------------------------------------------
# Help
# ------------------------------------------------------------

show_help() {

    print_header "Android Management Tool - Help"

    echo -e "${WHITE}Usage:${RESET} $0 [OPTION] [ARGUMENTS]"
    echo

    echo -e "${CYAN}Basic Information:${RESET}"
    echo "  --basic-info"
    echo "  --list-apps"
    echo "  --list-thirdparty-apps"
    echo "  --list-system-apps"

    echo

    echo -e "${CYAN}App Management:${RESET}"
    echo "  --remove-app PACKAGE"
    echo "  --remove-apps PACKAGE1 PACKAGE2 ..."
    echo "  --remove-default-apps"
    echo "  --disable-app PACKAGE"
    echo "  --enable-app PACKAGE"
    echo "  --app-info PACKAGE"

    echo

    echo -e "${CYAN}Permissions:${RESET}"
    echo "  --list-permissions"
    echo "  --app-permissions PACKAGE"
    echo "  --find-dangerous"
    echo "  --check-sensitive PACKAGE"

    echo

    echo -e "${CYAN}System Resources:${RESET}"
    echo "  --cpu-usage"
    echo "  --ram-usage"
    echo "  --storage-info"
    echo "  --battery-info"
    echo "  --running-processes"

    echo

    echo -e "${CYAN}Network:${RESET}"
    echo "  --network-connections"
    echo "  --network-port PORT"
    echo "  --active-connections"
    echo "  --firewall-status"

    echo

    echo -e "${CYAN}Security:${RESET}"
    echo "  --selinux-status"
    echo "  --device-logs"
    echo "  --clear-app-data PACKAGE"
    echo "  --backup-app PACKAGE"

    echo

    echo -e "${CYAN}Other:${RESET}"
    echo "  --interactive, -i"
    echo "  --version"
    echo "  --help, -h"

    echo

    echo -e "${WHITE}Examples:${RESET}"
    echo "  poirot --basic-info"
    echo "  poirot --list-apps"
    echo "  poirot --find-dangerous"
    echo "  poirot --app-info com.android.chrome"
    echo "  poirot --network-port 8080"
    echo "  poirot --interactive"
}

# ------------------------------------------------------------
# Version
# ------------------------------------------------------------

show_version() {

    echo "Android Management Tool v${VERSION}"
    echo "KYGnus"
}

# ------------------------------------------------------------
# Basic information
# ------------------------------------------------------------

get_basic_info() {

    check_device || return 1

    print_header "Basic Information About Android Device"

    echo -e "${INFO_ICON} Device Model: $(adb shell getprop ro.product.model)"
    echo -e "${INFO_ICON} Android Version: $(adb shell getprop ro.build.version.release)"
    echo -e "${INFO_ICON} Manufacturer: $(adb shell getprop ro.product.manufacturer)"
    echo -e "${INFO_ICON} Build Number: $(adb shell getprop ro.build.display.id)"
    echo -e "${INFO_ICON} Serial Number: $(adb get-serialno)"
    echo -e "${INFO_ICON} System Uptime: $(adb shell uptime)"
    echo -e "${INFO_ICON} Battery Level: $(adb shell dumpsys battery | grep level || true)"
    echo -e "${INFO_ICON} SELinux: $(adb shell getenforce)"
}

# ------------------------------------------------------------
# List applications
# ------------------------------------------------------------

list_installed_apps() {

    check_device || return 1

    print_header "All Installed Applications"

    adb shell pm list packages | sort
}

list_thirdparty_apps() {

    check_device || return 1

    print_header "Third-Party Applications"

    adb shell pm list packages -3 | sort
}

list_system_apps() {

    check_device || return 1

    print_header "System Applications"

    adb shell pm list packages -s | sort
}

# ------------------------------------------------------------
# Remove application
# ------------------------------------------------------------

remove_installed_app() {

    if [ -z "${1:-}" ]; then
        echo -e "${RED}${ERROR_ICON} Package name required.${RESET}"
        return 1
    fi

    check_device || return 1

    echo -e "${YELLOW}${WARNING_ICON} Removing $1...${RESET}"

    adb shell pm uninstall -k --user 0 "$1"

    echo -e "${GREEN}${CHECK_ICON} Removal attempted.${RESET}"
}

# ------------------------------------------------------------
# Remove multiple applications
# ------------------------------------------------------------

remove_multiple_apps() {

    if [ $# -eq 0 ]; then
        echo -e "${RED}${ERROR_ICON} Provide at least one package name.${RESET}"
        return 1
    fi

    check_device || return 1

    for app in "$@"; do

        echo -e "${INFO_ICON} Removing $app..."

        adb shell pm uninstall -k --user 0 "$app"

    done

    echo -e "${GREEN}${CHECK_ICON} Removal process completed.${RESET}"
}

# ------------------------------------------------------------
# Interactive removal
# ------------------------------------------------------------

remove_default_apps() {

    check_device || return 1

    print_header "Remove Applications"

    echo "Enter package names separated by spaces:"
    read -r -a default_apps

    for app in "${default_apps[@]}"; do

        echo -e "${INFO_ICON} Removing $app..."

        adb shell pm uninstall -k --user 0 "$app"

    done

    echo -e "${GREEN}${CHECK_ICON} Removal process completed.${RESET}"
}

# ------------------------------------------------------------
# Disable application
# ------------------------------------------------------------

disable_app() {

    if [ -z "${1:-}" ]; then
        echo -e "${RED}${ERROR_ICON} Package name required.${RESET}"
        return 1
    fi

    check_device || return 1

    echo -e "${INFO_ICON} Disabling $1..."

    adb shell pm disable-user --user 0 "$1"
}

# ------------------------------------------------------------
# Enable application
# ------------------------------------------------------------

enable_app() {

    if [ -z "${1:-}" ]; then
        echo -e "${RED}${ERROR_ICON} Package name required.${RESET}"
        return 1
    fi

    check_device || return 1

    echo -e "${INFO_ICON} Enabling $1..."

    adb shell pm enable "$1"
}

# ------------------------------------------------------------
# Application information
# ------------------------------------------------------------

app_info() {

    if [ -z "${1:-}" ]; then
        echo -e "${RED}${ERROR_ICON} Package name required.${RESET}"
        return 1
    fi

    check_device || return 1

    print_header "Information for $1"

    adb shell dumpsys package "$1"
}

# ------------------------------------------------------------
# Permissions
# ------------------------------------------------------------

list_all_permissions() {

    check_device || return 1

    print_header "All Android Permissions"

    adb shell pm list permissions -g
}

get_permissions_of_app() {

    if [ -z "${1:-}" ]; then
        echo -e "${RED}${ERROR_ICON} Package name required.${RESET}"
        return 1
    fi

    check_device || return 1

    print_header "Permissions for $1"

    adb shell dumpsys package "$1" |
        grep -E "permission|granted" |
        grep -v "installPermissions" || true
}

check_sensitive_permissions() {

    if [ -z "${1:-}" ]; then
        echo -e "${RED}${ERROR_ICON} Package name required.${RESET}"
        return 1
    fi

    check_device || return 1

    print_header "Sensitive Permissions for $1"

    local found=0

    local package_data

    package_data="$(adb shell dumpsys package "$1" 2>/dev/null || true)"

    for perm in "${SENSITIVE_PERMISSIONS[@]}"; do

        if printf '%s\n' "$package_data" | grep -q "$perm"; then

            echo -e "  ${RED}${WARNING_ICON} $perm${RESET}"

            found=1
        fi

    done

    if [ "$found" -eq 0 ]; then
        echo -e "${GREEN}No sensitive permissions found.${RESET}"
    fi
}

find_dangerous_permissions() {

    check_device || return 1

    print_header "Dangerous Permissions for Third-Party Applications"

    while IFS= read -r pkg; do

        [ -z "$pkg" ] && continue

        echo -e "${INFO_ICON} Permissions for $pkg:"

        local found=0
        local package_data

        package_data="$(adb shell dumpsys package "$pkg" 2>/dev/null || true)"

        for perm in "${SENSITIVE_PERMISSIONS[@]}"; do

            if printf '%s\n' "$package_data" | grep -q "$perm"; then

                echo -e "  ${RED}${WARNING_ICON} $perm${RESET}"

                found=1
            fi

        done

        if [ "$found" -eq 0 ]; then
            echo -e "  ${GREEN}No sensitive permissions found${RESET}"
        fi

        echo

    done < <(
        adb shell pm list packages -3 |
            awk -F: '{print $2}'
    )
}

# ------------------------------------------------------------
# CPU
# ------------------------------------------------------------

check_cpu_usage() {

    check_device || return 1

    print_header "CPU Usage - Top Processes"

    adb shell top -n 1 -d 1 | head -20
}

# ------------------------------------------------------------
# RAM
# ------------------------------------------------------------

check_ram_usage() {

    check_device || return 1

    print_header "RAM Usage"

    adb shell dumpsys meminfo |
        grep -E "Total RAM|Free RAM|Used RAM" || true
}

# ------------------------------------------------------------
# Storage
# ------------------------------------------------------------

storage_info() {

    check_device || return 1

    print_header "Storage Information"

    adb shell df -h
}

# ------------------------------------------------------------
# Battery
# ------------------------------------------------------------

battery_info() {

    check_device || return 1

    print_header "Battery Information"

    adb shell dumpsys battery
}

# ------------------------------------------------------------
# Processes
# ------------------------------------------------------------

running_processes() {

    check_device || return 1

    print_header "Running Processes"

    adb shell ps
}

# ------------------------------------------------------------
# Network
# ------------------------------------------------------------

find_network_connections() {

    check_device || return 1

    print_header "Network Connections"

    adb shell ss -tuna 2>/dev/null ||
        adb shell netstat -tuna 2>/dev/null ||
        echo "Network socket information unavailable."
}

find_network_connections_with_port() {

    if [ -z "${1:-}" ]; then
        echo -e "${RED}${ERROR_ICON} Port number required.${RESET}"
        return 1
    fi

    check_device || return 1

    print_header "Network Connections on Port $1"

    adb shell ss -tuna 2>/dev/null |
        grep -w ":$1" || true
}

active_connections() {

    check_device || return 1

    print_header "Active Network Connections"

    adb shell netstat 2>/dev/null |
        grep ESTABLISHED || true
}

# ------------------------------------------------------------
# Firewall
# ------------------------------------------------------------

firewall_status() {

    check_device || return 1

    print_header "Firewall Status"

    adb shell su -c "iptables -L" 2>/dev/null ||
        echo -e "${RED}${ERROR_ICON} Root access required or command unavailable.${RESET}"
}

# ------------------------------------------------------------
# SELinux
# ------------------------------------------------------------

selinux_status() {

    check_device || return 1

    print_header "SELinux Status"

    adb shell getenforce
}

# ------------------------------------------------------------
# Logs
# ------------------------------------------------------------

device_logs() {

    check_device || return 1

    print_header "Device Logs - Last 50 Lines"

    adb logcat -d -t 50
}

# ------------------------------------------------------------
# Clear application data
# ------------------------------------------------------------

clear_app_data() {

    if [ -z "${1:-}" ]; then
        echo -e "${RED}${ERROR_ICON} Package name required.${RESET}"
        return 1
    fi

    check_device || return 1

    echo -e "${YELLOW}${WARNING_ICON} Clearing data for $1...${RESET}"

    adb shell pm clear "$1"
}

# ------------------------------------------------------------
# Backup APK
# ------------------------------------------------------------

backup_app() {

    if [ -z "${1:-}" ]; then
        echo -e "${RED}${ERROR_ICON} Package name required.${RESET}"
        return 1
    fi

    check_device || return 1

    echo -e "${INFO_ICON} Backing up $1..."

    apk_path="$(adb shell pm path "$1" | head -n 1 | cut -d: -f2 | tr -d '\r')"

    if [ -n "$apk_path" ]; then

        adb pull "$apk_path" "$1.apk"

        echo -e "${GREEN}${CHECK_ICON} APK saved as $1.apk${RESET}"

    else

        echo -e "${RED}${ERROR_ICON} Could not find APK path for $1${RESET}"

        return 1
    fi
}

# ============================================================
# Interactive Menu
# ============================================================

interactive_menu() {

    while true; do

        clear

        print_header "Android Management Tool - Interactive Mode"

        echo -e "${CYAN}1.${RESET} Get Basic Information"
        echo -e "${CYAN}2.${RESET} List Applications"
        echo -e "${CYAN}3.${RESET} Remove / Disable Applications"
        echo -e "${CYAN}4.${RESET} Permission Analysis"
        echo -e "${CYAN}5.${RESET} System Resources"
        echo -e "${CYAN}6.${RESET} Network Operations"
        echo -e "${CYAN}7.${RESET} Security Operations"
        echo -e "${CYAN}8.${RESET} Exit"

        echo

        printf "${WHITE}Enter your choice (1-8): ${RESET}"

        read -r menu_choice

        case "$menu_choice" in

            1)
                get_basic_info
                ;;

            2)

                echo
                echo "1. All Applications"
                echo "2. Third-Party Applications"
                echo "3. System Applications"

                read -r sub_choice

                case "$sub_choice" in
                    1) list_installed_apps ;;
                    2) list_thirdparty_apps ;;
                    3) list_system_apps ;;
                    *) echo "Invalid choice." ;;
                esac

                ;;

            3)

                echo
                echo "1. Remove Application"
                echo "2. Remove Multiple Applications"
                echo "3. Disable Application"
                echo "4. Enable Application"

                read -r sub_choice

                case "$sub_choice" in

                    1)
                        read -r -p "Package name: " pkg
                        remove_installed_app "$pkg"
                        ;;

                    2)
                        read -r -a packages
                        remove_multiple_apps "${packages[@]}"
                        ;;

                    3)
                        read -r -p "Package name: " pkg
                        disable_app "$pkg"
                        ;;

                    4)
                        read -r -p "Package name: " pkg
                        enable_app "$pkg"
                        ;;

                    *)
                        echo "Invalid choice."
                        ;;

                esac

                ;;

            4)

                echo
                echo "1. Find Dangerous Permissions"
                echo "2. Check Application Permissions"
                echo "3. Check Sensitive Permissions"

                read -r sub_choice

                case "$sub_choice" in

                    1)
                        find_dangerous_permissions
                        ;;

                    2)
                        read -r -p "Package name: " pkg
                        get_permissions_of_app "$pkg"
                        ;;

                    3)
                        read -r -p "Package name: " pkg
                        check_sensitive_permissions "$pkg"
                        ;;

                    *)
                        echo "Invalid choice."
                        ;;

                esac

                ;;

            5)

                echo
                echo "1. CPU Usage"
                echo "2. RAM Usage"
                echo "3. Storage Information"
                echo "4. Battery Information"
                echo "5. Running Processes"

                read -r sub_choice

                case "$sub_choice" in
                    1) check_cpu_usage ;;
                    2) check_ram_usage ;;
                    3) storage_info ;;
                    4) battery_info ;;
                    5) running_processes ;;
                    *) echo "Invalid choice." ;;
                esac

                ;;

            6)

                echo
                echo "1. Network Connections"
                echo "2. Connections by Port"
                echo "3. Active Connections"

                read -r sub_choice

                case "$sub_choice" in

                    1)
                        find_network_connections
                        ;;

                    2)
                        read -r -p "Port: " port
                        find_network_connections_with_port "$port"
                        ;;

                    3)
                        active_connections
                        ;;

                    *)
                        echo "Invalid choice."
                        ;;

                esac

                ;;

            7)

                echo
                echo "1. SELinux Status"
                echo "2. Firewall Status"
                echo "3. Device Logs"

                read -r sub_choice

                case "$sub_choice" in
                    1) selinux_status ;;
                    2) firewall_status ;;
                    3) device_logs ;;
                    *) echo "Invalid choice." ;;
                esac

                ;;

            8)
                exit 0
                ;;

            *)
                echo -e "${RED}Invalid choice.${RESET}"
                ;;

        esac

        echo

        read -r -p "Press Enter to continue..."

    done
}

# ============================================================
# Argument Parser
# ============================================================

if [ $# -eq 0 ]; then

    show_help

    exit 0

fi

case "$1" in

    --help|-h)
        show_help
        ;;

    --version)
        show_version
        ;;

    --interactive|-i)
        interactive_menu
        ;;

    --basic-info)
        get_basic_info
        ;;

    --list-apps)
        list_installed_apps
        ;;

    --list-thirdparty-apps)
        list_thirdparty_apps
        ;;

    --list-system-apps)
        list_system_apps
        ;;

    --remove-app)
        remove_installed_app "${2:-}"
        ;;

    --remove-apps)
        shift
        remove_multiple_apps "$@"
        ;;

    --remove-default-apps)
        remove_default_apps
        ;;

    --disable-app)
        disable_app "${2:-}"
        ;;

    --enable-app)
        enable_app "${2:-}"
        ;;

    --app-info)
        app_info "${2:-}"
        ;;

    --list-permissions)
        list_all_permissions
        ;;

    --app-permissions)
        get_permissions_of_app "${2:-}"
        ;;

    --find-dangerous)
        find_dangerous_permissions
        ;;

    --check-sensitive)
        check_sensitive_permissions "${2:-}"
        ;;

    --cpu-usage)
        check_cpu_usage
        ;;

    --ram-usage)
        check_ram_usage
        ;;

    --storage-info)
        storage_info
        ;;

    --battery-info)
        battery_info
        ;;

    --running-processes)
        running_processes
        ;;

    --network-connections)
        find_network_connections
        ;;

    --network-port)
        find_network_connections_with_port "${2:-}"
        ;;

    --active-connections)
        active_connections
        ;;

    --firewall-status)
        firewall_status
        ;;

    --selinux-status)
        selinux_status
        ;;

    --device-logs)
        device_logs
        ;;

    --clear-app-data)
        clear_app_data "${2:-}"
        ;;

    --backup-app)
        backup_app "${2:-}"
        ;;

    *)
        echo -e "${RED}${ERROR_ICON} Unknown option: $1${RESET}"
        echo
        echo "Try:"
        echo "  poirot --help"
        exit 1
        ;;

esac
