#!/bin/bash

# prepbin: sign and entitle binaries in one line

# Copyright 2018 Foxlet Fox <foxlet@furcode.co>, GPL

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

OPTIND=1

if [ -z "$1" ]; then
    echo "Path to binary cannot be empty"
    exit 1
fi

ENTBODY="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n	<key>com.apple.lsapplicationworkspace.rebuildappdatabases</key>\n	<true/>\n	<key>com.apple.system-task-ports</key>\n	<true/>\n	<key>task_for_pid-allow</key>\n	<true/>\n	<key>com.apple.private.security.no-container</key>\n	<true/>\n	<key>platform-application</key>\n	<true/>\n	<key>get-task-allow</key>\n	<true/>\n	<key>com.apple.springboard.debugapplications</key>\n	<true/>\n	<key>com.apple.private.skip-library-validation</key>\n    <true/>\n</dict>\n</plist>"

BIN=$1
arch=`uname -p`
if [[ "$arch" == 'arm' ]]; then
    echo -e $ENTBODY > /tmp/default-ent.xml
    JTOOL=/usr/bin/jtool
    DEFAULTENT=/tmp/default-ent.xml
elif [[ "$arch" == 'arm64' ]]; then
    echo -e $ENTBODY > /tmp/default-ent.xml
    JTOOL=/usr/bin/jtool
    DEFAULTENT=/tmp/default-ent.xml
elif [[ "$arch" == 'i386' ]]; then
    JTOOL=$HOME/bin/jtool
    DEFAULTENT=$HOME/etc/prepbin/default-ent.xml
fi

jtool -e arch -arch arm64 $BIN
jtool --inplace --sign --ent $DEFAULTENT $BIN.arch_arm64
mv $BIN $BIN.arch_fat
mv $BIN.arch_arm64 $BIN
chmod +x $BIN
echo "$BIN has been signed and entitled"