#!/bin/sh

#  resign.sh
#  SignTool
#
#  Created by Harvey on 2018/5/8.
#  Copyright © 2018年 Harvey. All rights reserved.

ipaPath=$1
version=$2
bundleID=$3
displayName=$4
certificate=$5
buildVersion=$6
mobileprovisionUUID=$7
environment=$8
expired=$9
bundlePath=${10}/Contents

home=~

entitlementsPath="${home}/Library/MobileDevice/Provisioning Profiles/${mobileprovisionUUID}.mobileprovision.Entitlements.plist"
mobileprovisionPath="${home}/Library/MobileDevice/Provisioning Profiles/${mobileprovisionUUID}.mobileprovision"

cd $home
tmp=SignTool_Tmp
mkdir $tmp

cd $tmp

unzip -q -o ${ipaPath}

# 设置到期时间
if [ $expired != "default" ]; then
executableName=`/usr/libexec/PlistBuddy -c "Print :CFBundleExecutable" Payload/*.app/Info.plist`

cd Payload/*.app
mkdir Frameworks

unzip -q -o "$bundlePath/Resources/CertCheck.framework.zip" -d Frameworks
rm -rf Frameworks/__MACOSX

echo "${expired}" > Frameworks/CertCheck.framework/Sign.cc
$bundlePath/MacOS/yololib $executableName Frameworks/CertCheck.framework/CertCheck

cd ../..

fi

# 复制 mobileprovision
cp "${mobileprovisionPath}" Payload/*.app/embedded.mobileprovision

# 设置 bundleID
/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier ${bundleID}" Payload/*.app/Info.plist

# 改写 plist
if [ $version != "default" ]; then
/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString ${version}" Payload/*.app/Info.plist
fi

if [ $buildVersion != "default" ]; then
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion ${buildVersion}" Payload/*.app/Info.plist
fi

if [ $displayName != "default" ]; then
/usr/libexec/PlistBuddy -c "Add :CFBundleDisplayName string ${displayName}" Payload/*.app/Info.plist
/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName ${displayName}" Payload/*.app/Info.plist
fi

frameworks=(`find Payload/*.app/Frameworks -name "*.framework" -print`)
for framework in ${frameworks[*]}
do

echo "Sign for ${framework}"
codesign -f -s "${certificate}" $framework

done

# 签名
codesign -f -s "${certificate}" --entitlements "${entitlementsPath}" Payload/*.app

# 归档
newName="resign_${environment}_${bundleID}.ipa"
zip -qr "${newName}" Payload

movePath="${home}/Desktop/SignTool"
mkdir "${movePath}"

cp "${newName}" $movePath
open $movePath

cd ..
rm -rf $tmp
echo "签名完成"
