#!/bin/bash
set -e

script_dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
source "$script_dir/functions"
source "$script_dir/set-config.generated-config"

ENTITLEMENTS="$script_dir/$tbb_version_type.entitlements.xml"
app_name=$(Project_Name)

function check_signature() {
  LANG=$1
  UNZIP=$2
  local failed_open=0
  local failed_exec=0
  if [ ${UNZIP} -eq 1 ]
  then
    test -d test_${LANG} && rm -r test_${LANG}
    unzip -d test_${LANG} -q tb-${tbb_version}_$LANG.zip
    pushd test_${LANG}
  fi
  echo "Checking $LANG..."
  spctl -vvvv --assess --type open --context context:primary-signature "$app_name.app/"
  if [ $? -ne 3 ]; then
    echo tb-${tbb_version}_$LANG.zip not signed correctly. Failed open.
    failed_open=1
  fi
  spctl -vvvv --assess --type exec --context context:primary-signature "$app_name.app/"
  if [ $? -ne 0 ]; then
    echo tb-${tbb_version}_$LANG.zip not signed correctly. Failed exec.
    failed_exec=1
  fi
  if [ ${UNZIP} -eq 1 ]
  then
    popd
    rm -r test_${LANG}
  fi
  if [ ${failed_open} -ne 0 -o ${failed_exec} -ne 0 ]
  then
    return 1
  fi
}

cd ~/$SIGNING_PROJECTNAME-${tbb_version}

if test -n "$KEYCHAIN_PW"
then
  KPW="-p $KEYCHAIN_PW"
fi

security unlock $KPW /Users/torbrowser/Library/Keychains/tbb-signing-alpha.keychain
security unlock $KPW /Users/torbrowser/Library/Keychains/tbb-signing-2021.keychain

unset KPW KEYCHAIN_PW

for LANG in $bundle_locales
do
  if [ -f tb-${tbb_version}_${LANG}.zip ]
  then
    echo "Deleting tb-${tbb_version}_${LANG}.zip"
    rm tb-${tbb_version}_${LANG}.zip
  fi
  if [ -d "$app_name.app" ]
  then
    echo "Deleting $app_name.app"
    rm -r "$app_name.app"
  fi
  if [ -d "/Volumes/$app_name" ]; then
    echo "DMG already mounted. Please correct."
    exit 1
  fi
  hdiutil attach $(ProjectName)-${tbb_version}-macos_$LANG.dmg
  cp -rf "/Volumes/$app_name/$app_name.app" "$app_name.app"
  echo "Signing ${app_name}_${LANG}.app"
  codesign -vvv --deep -o runtime --entitlements="$ENTITLEMENTS" --timestamp -f -s "Developer ID Application: The Tor Project, Inc (MADPSAYN6T)" "$app_name.app/"
  echo "codesign exit code: $?"
  set +e
  check_signature $LANG 0
  if [ $? -eq 1 ]
  then
    echo Signature verification failed.
    rm -r "$app_name.app"
    hdiutil detach "/Volumes/$app_name"
    exit 1
  fi
  set -e
  echo "Zipping up tb-${tbb_version}_${LANG}.zip"
  zip -qr tb-${tbb_version}_${LANG}.zip "$app_name.app"
  rm -rf "$app_name.app"
  hdiutil detach "/Volumes/$app_name"
  set +e
  check_signature $LANG 1
  if [ $? -eq 1 ]
  then
    echo "Signature verification failed (${LANG})".
    rm -r "$app_name.app"
    exit 1
  fi
  set -e
done
