import os, sys, subprocess, shutil, time, re, random, json
from helpers import *

def hasArg(arg):
    return arg in sys.argv


if hasArg("--force") or hasArg("-f"):
    # If the user passed --force, we want to remove the validation file to ask them again
    VALIDATION_FILE = "/accounts/1000/shared/.installer/.term_prompt_asked"
    if os.path.exists(VALIDATION_FILE):
        os.remove(VALIDATION_FILE)

# Create file to validate if we already asked the user or not
VALIDATION_FILE = "/accounts/1000/shared/.installer/.term_prompt_asked"
if os.path.exists(VALIDATION_FILE):
    # We already asked the user, no need to do it again
    exit(0)

result = showDialog(
    id="dlg",
    title="Automate restore script?",
    message="If you select yes, Term49 will run all the scripts necessary for restoration automatically, allowing to preserve root/impersonation etc...",
    buttons=[
        {
            "label": "Yes",
        },
        {
            "label": "No"
        }
    ]
)

with open(VALIDATION_FILE, "w") as f:
    f.write("asked")

if result["resp_obj"]["responseBtnLabel"] == "Yes":
    runAs("/accounts/1000/shared/.installer/setup.sh", getImpersonation("user", "apps"))
    showDialog(
        id="success",
        title="Success",
        message="Term49 should now be setup to run the restore script on launch. Just open Term49 and it should do everything for you!",
        buttons=[
            {
                "label": "OK"
            }
        ]
    )