#!/bin/bash

function help {
    echo "Syntax: bfdecrypt [-p PID | -P appname]"
    echo
    echo For example:
    echo "bfdecrypt -P Reddit.app # decrypts the Reddit app"
    echo
    echo "Instead of specifying the PID with -p, bfdecrypt can search for the correct PID based on the app name."
    echo "Just enter \"-P identifier\" where \"identifier\" is a string unique to your app, e.g. \"fing.app\"."
echo
echo "The app you are decrypting must be open beforehand!"
}

if [ "$1" != "-p" ] && [ "$1" != "-P" ]; then
    help
    exit 1
fi

if [ "$1" == "-p" ]; then
    PID=$2
else
echo "[*] If the app crashes upon injection, try using -p to input the app's PID instead"
    count=`ps axwww|grep "$2"|grep container|grep '.app'|grep -v grep |wc -l|sed 's/ //g'`
    if [ "$count" != "1" ]; then  
        echo "[!] \"$2\" was not uniquely found, please check your criteria."
        exit 1
    fi
    PID=`ps awwwx|grep "$2"|grep container|grep '.app'|grep -v grep|sed 's/^\ *//g'|cut -f1 -d\ `
    bad=1
    case "$PID" in
        ''|*[!0-9]*) bad=1 ;;
        *) bad=0 ;;
    esac
    if [ "$bad" != "0" ]; then
        echo "[!] Process not found for string \"$3\""
        exit 1
    fi
fi

echo "Injection done! Open the app and wait to start decryption."
sleep 7s
/electra/inject_criticald "$PID" /Library/MobileSubstrate/DynamicLibraries/bfdecrypt.dylib > /dev/null 2>&1