#!/var/jb/usr/bin/bash

# FUNCTIONS
ipatool_auth () {
    if [[ ! -e "$azule/ipatool_authenticated" || -n "$IPATOOL_EMAIL" ]]; then
            
        # VARIABLE CHECK
        if [ -z "$IPATOOL_EMAIL" ]; then while
            printf '[*] Apple ID: '
            read -r IPATOOL_EMAIL
            [ -z "$IPATOOL_EMAIL" ] && Announce "No Apple ID Provided"
        do true; done; fi

        if [ -z "$IPATOOL_PASSWORD" ]; then while
            printf '[*] Password for Apple ID: '
            read -r -s IPATOOL_PASSWORD
            [ -z "$IPATOOL_PASSWORD" ] && Announce "No Password Provided"
        do true; done; fi
        printf "\n"

        ipatool auth login -e "$IPATOOL_EMAIL" -p "$IPATOOL_PASSWORD" &>/dev/null
        Verbose "Succesfully Authenticated" "Failed Authenticating" 34
        echo -n > "$azule/ipatool_authenticated"
    fi
}

# INSTALLING UPDATES AND DECRYPTION
ipadir="$(basename "$ipadir")"
if [ -z "$ignore_outdated" ]; then
    Announce "Checking for App Updates..."

    # CHECK IF APP IS INSTALLED
    while read -r i; do
        MCMMetadataIdentifier="$(ExtractPlistValue MCMMetadataIdentifier "$i")"
        if [ "${MCMMetadataIdentifier,,}" = "${ipadir,,}" ]; then
            info_plist="$(find "$(dirname "$i")"/*.app/ -maxdepth 1 -name Info.plist)"
            thinned="$(ExtractPlistValue variantID "$(dirname "$i")/iTunesMetadata.plist")"
            break
        fi
    done < <(find /var/containers/Bundle/Application -name .com.apple.mobile_container_manager.metadata.plist)
    
    # CHECK IF APP IS OUTDATED
    if ! network_check; then Announce "No Connection to the Internet" 26; fi
    latestv="$(curl -s "http://itunes.apple.com/lookup?bundleId=$ipadir&country=$country_code" | jq -r '.results[].version')"
    currentv="$(ExtractPlistValue CFBundleShortVersionString "$info_plist")"

    # VARIABLE CHECK
    if [ -z "$latestv" ] && [ -z "$currentv" ]; then Announce "Invalid App" 8; fi

    # UPDATING OUTDATED APPS
    if [ -n "$outdated" ] || { [ -n "$latestv" ] && [[ "$latestv" != "$currentv" || -n "$thinned" ]]; }; then
        Announce "Update Available"
        ipatool_auth

        # DOWNLOAD AND INSTALL UPDATES
        Announce "Downloading $ipadir..."
        ipatool download -b "$ipadir" -c "$country_code" --purchase --output "$dir/$ipadir.ipa" 
        status="$?"
        if [ "$status" == "1" ]; then
            rm -f "$azule/ipatool_authenticated"
            ipatool_auth
            ipatool download -b "$ipadir" -c "$country_code" --purchase --output "$dir/$ipadir.ipa"
            status="$?"
        fi
        
        Verbose "Downloaded $ipadir" "Couldn't Download $ipadir" 28 -x

        # CHECK & PATCH MINIMUM VERSION AND TEMPORARILY REMOVE UISUPPORTEDDEVICES
        mkdir -p "$dir/minverplist/"
        unzip -qq "$dir/$ipadir.ipa" "Payload/*.app/Info.plist" -d "$dir/minverplist/"
        cd "$dir/minverplist/" || exit
        cp -a Payload/*.app/Info.plist "$dir"/minverplist/

        UISupportedDevices1="$(ExtractPlistValue UISupportedDevices "$dir"/minverplist/Payload/*.app/Info.plist)"
        if [ -n "$UISupportedDevices1" ]; then
            RemovePlistKey UISupportedDevices Payload/*.app/Info.plist
            Verbose "Temporarily Removed UISupportedDevices from app" "Couldn't remove UISupportedDevices from app" 37 -v 
        fi

        current_ios_version="$(sw_vers -productVersion)"
        orig_min_version="$(ExtractPlistValue MinimumOSVersion "$dir"/minverplist/Payload/*.app/Info.plist)"
        if verlt "$current_ios_version" "$orig_min_version"; then
            ReplacePlistValue "$current_ios_version" MinimumOSVersion Payload/*.app/Info.plist
            Verbose "Temporarily changed $ipadir's Minimum OS Version to $current_ios_version" "Couldn't change $ipadir's Minimum OS Version" 35 -v
            changed_min_version=1
        fi

        if [ -n "$changed_min_version" ] || [ -n "$UISupportedDevices1" ]; then
            zip -qq -u "$dir/$ipadir.ipa" Payload/*.app/Info.plist
        fi

        cd "$dir" || exit

        Announce "Installing $ipadir ..."
        appinst "$dir/$ipadir.ipa" &>/dev/null
        Announce "Installed $ipadir"
    else
        Announce "No Updates Available"
    fi
fi

# DECRYPTION: GET MAIN INFO.PLIST
while read -r i; do
    MCMMetadataIdentifier="$(ExtractPlistValue MCMMetadataIdentifier "$i")"
    if [ "${MCMMetadataIdentifier,,}" = "${ipadir,,}" ]; then
        foul_plist="$(find "$(dirname "$i")"/*.app/ -maxdepth 1 -name Info.plist)"
        break
    fi
done < <(find /var/containers/Bundle/Application -name .com.apple.mobile_container_manager.metadata.plist)

if [ -z "$foul_plist" ]; then Announce "App Not Found" 8; fi

# DECRYPT
mkdir -p Payload
appname="$(basename "$(dirname "$foul_plist")")"

while read -r i; do
    CFBundleExecutable="$(ExtractPlistValue CFBundleExecutable "$i")"
    DTPlatformName="$(ExtractPlistValue DTPlatformName "$i")"
    if [ -n "$CFBundleExecutable" ] && [ -e "$(dirname "$i")/$CFBundleExecutable" ] && otool -l "$(dirname "$i")/$CFBundleExecutable" | grep -q 'cryptid 1' && [ "$DTPlatformName" != "watchos" ]; then
        if [ -z "$dexec" ]; then

            # CHOOSING FOULDECRYPT BINARY
            ios_version="$(sw_vers -productVersion)"
            if [[ "${ios_version%.*}" -lt "14" ]] || [[ ! -e "/.installed_taurine" && ! -e "/.installed_unc0ver" ]]; then
                decrypt="fouldecrypt.tfp0"
            elif [ -e "/.installed_taurine" ]; then
                decrypt="fouldecrypt.kernrw"
            elif [ -e "/.installed_unc0ver" ]; then
                decrypt="fouldecrypt.krw"
            fi
            
            Announce "Chose $decrypt as decryptor" -v
            Announce "Decrypting App..."
        fi

        mkdir -p "Payload/$(dirname "$i" | sed "s|^.*$appname|$appname|")"
        Announce "Decrypting $CFBundleExecutable..." -v
        "$decrypt" -v "$(dirname "$i")/$CFBundleExecutable" "Payload/$(dirname "$i" | sed "s|^.*$appname|$appname|")/$CFBundleExecutable" &>/dev/null
        status="$?"
        if [ "$status" != "0" ]; then
            qv=$(( qv + 1 ))
        fi
        Verbose "Decrypted $CFBundleExecutable" "Couldn't Decrypt $CFBundleExecutable" -v -x
        dexec=1
    fi
done < <(find "$(dirname "$foul_plist")" -name "Info.plist")

cp -a -n "$(dirname "$foul_plist")" Payload
status="$qv"
Verbose "Finished Decryption" "Could Not decrypt $qv files. This may cause problems later on" -x

# RESTORING MIN VERSION
if [[ -n "$changed_min_version" || -n "$UISupportedDevices1" ]]; then
    mv "$dir"/minverplist/Info.plist Payload/"$appname"/Info.plist
    Verbose "Restored Original Plist Values" "Couldn't Restore Original Plist Values" -v
fi

full_unzipped=1