import shutil
import sys
import subprocess

from .util import *
from .assemble_apk import assemble_apk

def align_apk():
    updated = assemble_apk()
    
    if not updated and Path(ALIGNED_APK).exists():
        print("Skipping alignment")
        return False
    
    # Align the APK
    print("Aligning APK...")
    ALIGNED_APK.parent.mkdir(exist_ok=True)
    res = subprocess.run([ZIPALIGN, '-pvf', '4', ASSEMBLED_APK, ALIGNED_APK])
    if res.returncode != 0:
        print("Error ocurred while aligning")
        exit(res.returncode)
    
def sign_apk():
    updated = align_apk()
    
    # Check what kind of signing the user wants us to do
    arg = sys.argv[1] if len(sys.argv) > 1 else ''
    if 'd' in arg:
        keystore_params = ['--ks', 'keystores/debug.keystore', '--ks-pass', 'pass:123456']
        signed_apk = SIGNED_APK_DEBUG
    elif 'r' in arg:
        keystore_params = ['--ks', 'keystores/debug.keystore',]
        signed_apk = SIGNED_APK
    else:
        print("WARNING: Neither 'r' (release) nor 'd' (debug) was specified for the second parameter so the aligned apk will not be signed.")
        print("STOP.")
        exit(0)
    
    if not updated and Path(signed_apk).exists():
        print("Skipping signing")
        return False
    
    
    # Sign the APK
    print("Signing APK...")
    shutil.copy(ALIGNED_APK, signed_apk)
    SIGNED_APK.parent.mkdir(exist_ok=True)
    _ = subprocess.run([JAVA_BIN, '-jar', APKSIGNER, 'sign', *keystore_params, signed_apk])