#!/bin/sh

# setup

APP_NAME="$1" # engin short name i.e. Chrome
ENGIN_PATH="$3" # engin path i.e. /Applications/Google Chrome.app
ENGIN_NAME="$4" # engin name i.e. Google Chrome
APP_CONTENT="$2/$APP_NAME.app/Contents"
ENGIN_SMALL_NAME="$5" # engin short name i.e. Chrome
FRAMEWORK_NAME="$6" #framework name i.e. Google Chrome Framework.framework

#cleanup

rm -rf "$APP_CONTENT"

# creating app wrapper

mkdir -p "$APP_CONTENT/MacOS"
mkdir -p "$APP_CONTENT/Frameworks"
mkdir -p "$APP_CONTENT/Resources"


# copying files

cp -Rf "$ENGIN_PATH/Contents/Info.plist" "$APP_CONTENT/Info.plist"
cp -Rf "$ENGIN_PATH/Contents/Resources" "$APP_CONTENT/"
cp -Rf "$2/icon.icns" "$APP_CONTENT/Resources/icon.icns"
#cp -Rf "$ENGIN_PATH/Contents/MacOS/$ENGIN_NAME" "$APP_CONTENT/MacOS/"

plutil -replace "CFBundleIconFile" -string "icon.icns" "$APP_CONTENT/Info.plist"
plutil -replace "CFBundleName" -string "$APP_NAME" "$APP_CONTENT/Info.plist"
plutil -replace "CFBundleDisplayName" -string "$APP_NAME" "$APP_CONTENT/Info.plist"
plutil -remove "CFBundleURLTypes" "$APP_CONTENT/Info.plist"
plutil -remove "NSUserActivityTypes" "$APP_CONTENT/Info.plist"
plutil -remove "CFBundleDocumentTypes" "$APP_CONTENT/Info.plist"
plutil -remove "DTSDKBuild" "$APP_CONTENT/Info.plist"
plutil -remove "DTSDKName" "$APP_CONTENT/Info.plist"
plutil -remove "DTXcode" "$APP_CONTENT/Info.plist"
plutil -remove "DTXcodeBuild" "$APP_CONTENT/Info.plist"
plutil -remove "KSChannelID-full" "$APP_CONTENT/Info.plist"
plutil -remove "KSProductID" "$APP_CONTENT/Info.plist"
plutil -remove "KSUpdateURL" "$APP_CONTENT/Info.plist"
plutil -remove "KSVersion" "$APP_CONTENT/Info.plist"

xattr -rds com.apple.quarantine "$2/$APP_NAME.app"

/usr/bin/codesign --force --deep --verbose --sign "-" "$2/$APP_NAME.app"

# creating symlinks for internal resources

#ln -s "$ENGIN_PATH/Contents/Versions" "$APP_CONTENT/"
#ln -s "$ENGIN_PATH/Contents/PkgInfo" "$APP_CONTENT/"
#ln -s "$ENGIN_PATH/Contents/Helpers" "$APP_CONTENT/"
#ln -s "$ENGIN_PATH/Contents/_CodeSignature" "$APP_CONTENT/"
ln -s "$ENGIN_PATH/Contents/MacOS/$ENGIN_NAME" "$APP_CONTENT/MacOS/"
ln -s "$ENGIN_PATH/Contents/Frameworks/$FRAMEWORK_NAME" "$APP_CONTENT/Frameworks/"


# replace name

#for f in "$APP_CONTENT/Resources/"*.lproj/*.strings; 
#do
#	sed -i '' "s/CFBundleDisplayName = \"$ENGIN_NAME\"/CFBundleDisplayName = \"$APP_NAME\"/g" "$f"
#	sed -i '' "s/CFBundleName = \"$ENGIN_SMALL_NAME\"/CFBundleName = \"$APP_NAME\"/g" "$f"
#done


