#!/usr/bin/env bash 
set -o errexit
set -o pipefail

INSPECT_ONLY=0
if [[ "$1" == '-i' ]]; then
    INSPECT_ONLY=1
    shift
fi

if [[ "$1" == '-l' ]]; then
    security find-certificate -a | awk '/^keychain/ {if(k!=$0){print; k=$0;}} /"labl"<blob>=/{sub(".*<blob>=","          "); print}'
    exit
fi

if [[ ! ( # any of the following are not true
        # 1st arg is an existing regular file
        -f "$1" &&
        # ...and it has a .ipa extension
        "${1##*.}" == "ipa" &&
        # 2nd arg is an existing regular file
        ($INSPECT_ONLY == 1 || -f "$2") &&
        # ...and it has an .mobileprovision extension
        ($INSPECT_ONLY == 1 || "${2##*.}" == "mobileprovision") &&
        # 3rd arg is a non-empty string
        ($INSPECT_ONLY == 1 || -n "$3") &&
        # 4th arg (if provided) must end with .ipa
        ($INSPECT_ONLY == 1 || -z "${4:-}" || "${4##*.}" == "ipa")
        ) ]]; then
    cat << EOF >&2
    Usage: $(basename "$0") Application.ipa foo/bar.mobileprovision "iPhone Distribution: I can haz code signed" [output_path]
    Usage: $(basename "$0") -i Application.ipa

    Options:
      -i    Only inspect the package. Do not resign it.
      -l    List certificates and exit

    Notes:
      - [output_path] (optional) must end with .ipa if specified.
EOF
    exit;
fi

## Exit on use of an uninitialized variable
set -o nounset
## Exit if any statement returns a non-true return value (non-zero)
set -o errexit
## Announce commands
#set -o xtrace

realpath(){
    echo "$(cd "$(dirname "$1")"; echo -n "$(pwd)/$(basename "$1")")";
}

IPA="$(realpath $1)"
TMP="$(mktemp -d /tmp/resign.$(basename "$IPA" .ipa).XXXXX)" # /tmp/resign.myapp.XYZ12
IPA_NEW="${4:-$(pwd)/$(basename "$IPA" .ipa).resigned.ipa}"  # 如果未提供 $4，则使用默认路径
CLEANUP_TEMP=0 # Do not remove this line or "set -o nounset" will error on checks below
#CLEANUP_TEMP=1 # Uncomment this line if you want this script to clean up after itself
cd "$TMP"
[[ $CLEANUP_TEMP -ne 1 ]] && echo "Using temp dir: $TMP"
unzip -q "$IPA"
plutil -convert xml1 Payload/*.app/Info.plist -o Info.plist
echo "App has BundleDisplayName '$(/usr/libexec/PlistBuddy -c 'Print :CFBundleDisplayName' Info.plist)' and BundleShortVersionString '$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' Info.plist)'"
echo "App has BundleIdentifier  '$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' Info.plist)' and BundleVersion $(/usr/libexec/PlistBuddy -c 'Print :CFBundleVersion' Info.plist)"
security cms -D -i Payload/*.app/embedded.mobileprovision 2>/dev/null > mobileprovision.plist
echo "App has provision         '$(/usr/libexec/PlistBuddy -c "Print :Name" mobileprovision.plist)', which supports '$(/usr/libexec/PlistBuddy -c "Print :Entitlements:application-identifier" mobileprovision.plist)'"
if [[ ! ($INSPECT_ONLY == 1) ]]; then
    PROVISION="$(realpath "$2")"
    CERTIFICATE="$3"
    security cms -D -i "$PROVISION" 2>/dev/null> provision.plist
    /usr/libexec/PlistBuddy  -x -c 'Print :Entitlements' provision.plist > entitlements.plist
    echo "Embedding provision       '$(/usr/libexec/PlistBuddy -c "Print :Name" provision.plist)', which supports '$(/usr/libexec/PlistBuddy -c "Print :Entitlements:application-identifier" provision.plist)'"
    rm -rf Payload/*.app/_CodeSignature Payload/*.app/CodeResources
    cp "$PROVISION" Payload/*.app/embedded.mobileprovision

    # 签名 Frameworks 文件夹（如果存在）
    FRAMEWORKS_DIR=(Payload/*.app/Frameworks)
    if [[ -d "${FRAMEWORKS_DIR[0]}" ]]; then
        /usr/bin/codesign -f -s "$CERTIFICATE" Payload/*.app/Frameworks/*
    else
        echo "Frameworks folder not found, skipping."
    fi
    # 签名 Plugins 文件夹（如果存在）
    PLUGINS_DIR=(Payload/*.app/Plugins)
    if [[ -d "${PLUGINS_DIR[0]}" ]]; then
        /usr/bin/codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/*.app/Plugins/*
    else
        echo "Plugins folder not found, skipping."
    fi
    # 签名主应用程序
    /usr/bin/codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/*.app


    # 定义需要删除的临时文件列表
    TEMP_FILES=(
        "entitlements.plist"
        "mobileprovision.plist"
        "Info.plist"
        "provision.plist"
    )

    # 遍历并删除临时文件（仅在当前临时目录下删除，不递归）
    for file in "${TEMP_FILES[@]}"; do
        if [[ -f "$file" ]]; then
            echo "Deleting temporary file: $file"
            rm "$file"
        fi
    done

    # 将 Payload 目录及其同级内容重新打包
    cd "$TMP"  # 切换到解压后的根目录
    zip -qr "$IPA_NEW" ./*  # 压缩当前目录下的所有内容
    echo "Resigned IPA saved to $IPA_NEW"
    
fi
if [[ $CLEANUP_TEMP -eq 1 ]]; then
    rm -rf "$TMP"
fi
