#!/bin/bash
# 2019/07/01
# update for 6.4 & big sur
function listCN {
   KEYCHAIN_NAME=$1
   if [[ -z $KEYCHAIN_NAME ]]; then
      KEYCHAIN_NAME=`security default-keychain` #"login.keychain"
   fi
   echo "The common names in the keychain $KEYCHAIN_NAME are listed below, please copy the one to sign the app"
   certtool y k=login.keychain | grep Common\ Name
   exit 0
}

function prepareFiles {

   echo "Extracting license..."

#extrace license from current dmg, remove blkx node which is related to current dmg
#the generated license.xml will be used for the new dmg

   hdiutil udifderez -xml $DMGFile > license_original.xml
   ignore=false
   while IFS= read -r line;do
      if ! "$ignore"; then
         if [[ "$line" == *"<key>blkx</key>"* ]]; then
            ignore=true
         fi
         if ! "$ignore"; then
            echo "$line" >> license_resource.xml
         fi
      else
         if [[ "$line" == *"</array>"* ]]; then
            ignore=false
         fi
      fi
   done < "license_original.xml"

   echo "trying to mount the $DMGFile"

   list=$(hdiutil attach $DMGFile 2>&1 | tail -1l)
   read -r -a paths <<<"$list"

   for i in "${paths[@]}"; do
      #echo $i
      if [[ $i == *"Volume"* ]]; then #$i =~ .*Volume.*
         mountedPath=$i
         break
      fi
   done

   if [[ -z $mountedPath ]]; then
      echo "Something went wrong, can't find the mounted dmg."
      exit 1
   else
      echo "The dmg is mounted into $mountedPath"
   fi

   appfilename=`ls -1 $mountedPath | grep .app`

   echo "Cleaning up the temorary directory $TMPDIR"
   [ -a "$TMPDIR" ] && ( rm -r $TMPDIR ) #echo Please remvoe the tmp folder; exit 1 )
   mkdir -p $TMPDIR

   echo "Coping all files into the temporary folder"
   ditto $mountedPath $TMPDIR

   echo "Copying the entitlements"
   FilePath=`ls -1 $mountedPath | grep .app`
   FilePathEscaped=$(printf %q "$(ls -1 $mountedPath | grep .app)")
   #FilePathEscaped=$(printf %q $FilePath)
   #echo "$mountedPath/$FilePathEscaped/⁨Contents/Resources/bria.entitlements"
   eval cp "$mountedPath/$FilePathEscaped/Contents/Resources/bria.entitlements" .
   #eval cp "$mountedPath/$FilePathEscaped/Contents/Resources/sla.r" .

   echo "Unmount the $mountedPath"
   hdiutil detach -force $mountedPath
}

function doSign {
   echo "Codesign using certificate $CERT_NAME ..."

   file=$TMPDIR/$FilePath/Contents/Frameworks/
   file2=GlanceFramework.framework
   if [[ -d "$file$file2" ]]; then
      echo "codesign $file$file2"
      eval $(/usr/bin/codesign --timestamp -o runtime --entitlements bria.entitlements --deep -fv -s "$CERT_NAME" "$file$file2")
   fi

   file2=Squirrel.framework/Resources/ShipIt
   if [[ -f "$file$file2" ]]; then
      echo "codesign $file$file2"
      eval $(/usr/bin/codesign --timestamp -o runtime --entitlements bria.entitlements -fv -s "$CERT_NAME" "$file$file2")
   fi

   files=(AppCenter.framework AppCenterCrashes.framework CocoaLumberjack.framework CPCAPI2.framework DSCapture.framework GTLR.framework MacFreeRDP.framework Mantle.framework ReactiveCocoa.framework Squirrel.framework SVGKit.framework)
   for f in ${files[@]}; do
      if [[ -d "$file$f" ]]; then
         echo "codesign $file$f"
         eval $(/usr/bin/codesign --timestamp -o runtime --entitlements bria.entitlements -fv -s "$CERT_NAME" "$file$f")
      fi
   done
#sign the app
   file=$TMPDIR/$FilePath/Contents/MacOS/
   #file2=$(basename -s .app $appfilename)
   file2=${appfilename%.*}
   echo "codesign $file$file2"
   eval $(/usr/bin/codesign --timestamp -o runtime --entitlements bria.entitlements -fv -s "$CERT_NAME" "$file$file2")
   echo "codesign $TMPDIR/$FilePath"
   eval $(/usr/bin/codesign --timestamp -o runtime --entitlements bria.entitlements -fv -s "$CERT_NAME" "$TMPDIR/$FilePath")

   if [ $? != 0 ]; then
   error "Codesign failed - see preceding error."
   exit 1
   fi

   echo "Codesign succeeded"
}

function makeDMG {
   echo "Packaging the new dmg"
   volumeName=$(basename $mountedPath)
   DMGFileNew=${DMGFile/.dmg/_Resigned.dmg}

   hdiutil create -megabytes 200 -ov -fs HFS+ -volname $volumeName -attach $DMGFileNew

   #copy everything into the new dmg
   ditto $TMPDIR $mountedPath

   #format the dmg with background and size
   #/usr/bin/php dmgsetup.php $volumeName "$appfilename" - monterey does not have built in php
   php dmgsetup.php $volumeName "$appfilename"

   #un-mount the new dmg
   hdiutil detach -force $mountedPath

   DMGFileAuth=${DMGFileNew/.dmg/_Notarize.dmg}
   hdiutil convert $DMGFileNew -format UDBZ -o $DMGFileAuth

   #add the license agreement to the dmg
   #hdiutil unflatten $DMGFileAuth
   #Rez -a sla.r -o $DMGFileAuth
   #hdiutil flatten $DMGFileAuth
   hdiutil udifrez -xml license_resource.xml '' $DMGFileAuth

   #sign the dmg
   #/usr/bin/codesign --timestamp -fv -s "Developer ID Application: CounterPath Corporation" BriaNew.dmg
   eval $(/usr/bin/codesign --timestamp -fv -s "$CERT_NAME" "$DMGFileAuth")
   rm "$DMGFileNew"
   echo "The $DMGFileAuth with your own certificate is ready for notarization. "
}

echo Notarization starts...
# check arguments
while [[ $# -ge 1 ]]
do
key="$1"

case $key in
-k)
KEYCHAIN_NAME="$2"
listCN $2
shift # past argument
;;
-d)
DMGFile="$2"
echo $DMGFile
CERT_NAME="$3"
echo $CERT_NAME
if [[ -z $DMGFile || ! -f $DMGFile || -z $CERT_NAME ]]; then
echo "Run: $0 [-d bundle_name.dmg \"certificate_common_name\"]"
exit 0
fi

TMPDIR="tmp"

prepareFiles
doSign
makeDMG

rm "bria.entitlements"
rm "license_resource.xml"
rm "license_original.xml"

rm -r "$TMPDIR"

exit 0

shift # past argument
;;
-u)
DMGFile="$2"
KeyChain_Profile="$3"

#echo "$DMGFile   $KeyChain_Profile
if [[ -z $DMGFile || -z $KeyChain_Profile ]]; then
   echo "Run: $0 [-u bundle_name.dmg keychain_profile_name]"
   exit 0
fi

echo "Submitting the app for notarization, this may take a few minutes..."
result=`xcrun notarytool submit $DMGFile --keychain-profile $KeyChain_Profile --wait 2>&1`

echo "Notarization result: "

echo "$result"

if [ $? -eq 0 ]; then
   if [[ $result == *"status: Accepted"* ]]; then
      echo "Notarization succeeded, stapling it..."
      /usr/bin/stapler staple $DMGFile
      if [ $? != 0 ]; then
         echo "Stapling failed, someting went wrong"
      fi
   fi
fi

exit 0
shift # past argument
;;
*)
# unknown option
echo "Please refer to the manual to use the script."
;;
esac
shift # past argument or value
done
exit 0
