# Function to perform post-compile tasks:
# To be invoked inside a package build file.
mkfinalpkg() {
   # Now we attempt to split the total time we'll get when making the summary into two times: compile time and
   # packaging time. Here we store the value of $SECONDS variable the moment makefinalpkg is invoked. We use this
   # value as the compile time, because this is the next function that's called by the build script the moment a 
   # successful compile make install  DESTDIR=$PKG or something similar. 

   # SM_COMPILETIMEA will store the exact seconds
   SM_COMPILETIMEA="$SECONDS"

   # SM_COMPILETIMEB will run the runtime function against SM_COMPILETIMEA and store the resulting output
   SM_COMPILETIMEB="$( runtime $SM_COMPILETIMEA )"

   echo "[INFO] Leaving build directory $SM_TMP"
   echo "[INFO] Entering staging directory $PKG"
   cd $PKG
   echo "[INFO] Just a min..."
   echo "[INFO] Copying post-install files..."
   mkdir -p "$PKG/install"

   for f in doinst.sh ; do
     [ -e "$SRCDIR/$f" ] && cp "$SRCDIR/$f" "$PKG/install/"
   done

   # Compress and link manpages
   if [ -d "$PKG/share/man" ]; then
     echo "[INFO] Compressing and linking man pages..."
        ( cd "$PKG/share/man"
           for manpagedir in $(find . -type d -name "man*") ; do
           ( cd "$manpagedir"
           for eachpage in $( find . -type l -maxdepth 1) ; do
               ln -s "$( readlink "$eachpage" ).gz" "$eachpage".gz
                     rm "$eachpage"
           done
           gzip -9 ./*.? >/dev/null 2>&1 || true
          )
         done
        )
   fi
   
   SM_TOTALFILECOUNT="$(find $PKG -type f | wc -l)"
   SM_TOTALDIRCOUNT="$(find $PKG -type d | wc -l)"
   SM_TOTALSYMCOUNT="$(find $PKG -type l | wc -l)"
   SM_PACKUSIZE1="$(du -s $PKG | awk '{print $1}')"

   # Remove .la files similar to what slackware devs are doing in slackware-current, but in a more efficient manner :)
   echo "[INFO] Discarding any libtool archive (.la) files..."
   find "$PKG" ! -type d -name "*.la" -exec rm -v {} \;

   # Provide a copy of the package build file so that users know the build options that went into compiling the package
   install -Dm 644 "$SRCDIR/$APP.SMBuild" "$PKGDOCS/$APP.SMBuild"

   # Now strip the binaries and shared libraries
   if [ -z "$SM_DEBUG" ] && [ "$SM_DEBUG" != "1" ]; then
     find "$PKG" -print0 | xargs -0 file -m /etc/file/magic/elf | \
     grep -E "executable|shared object|statically linked" | grep "ELF" | \
     cut -d: -f1 | xargs strip --strip-unneeded 2>/dev/null || true
   fi

   # And static libraries separately unconditionally
   find "$PKG" -print0 | xargs -0 file -m /etc/file/magic/archive | \
   grep -E "current ar archive" | awk '{print $1}' | cut -d: -f1 | \
   xargs strip --strip-unneeded 2>/dev/null || true

   # Here we ascertain the packaging time taken to actually prepare the final package. For this, we must reset the
   # SECONDS variable to ensure accuracy
   SECONDS=0

   # Finally create the package
   /bin/makepkg -l y -c n "$PKGDEST/$APP-$VERSION-$ARCH-$BUILD.$PKGEXT"
   SM_PKGSTATUS=$?

   # Store package location inside this variable:
   SM_PACKLOCATION="$PKGDEST/$APP-$VERSION-$ARCH-$BUILD.$PKGEXT"
  
   echo "[INFO] Leaving staging directory $PKG"

   # cd back to $SRCDIR when SM_PRESERVEPACKAGEDIR is set to 0 to prevent this error: shell-init: error retrieving
   # current directory: getcwd: cannot access parent directories: No such file or directory
   echo "[INFO] Re-entering source directory $SRCDIR"
   cd "$SRCDIR"

   # Discard $APP.APP, $APP.BUILD and $APP.VERSION files if SM_AUTOBUILDTEMP is not set. If SM_AUTOBUILDTEMP is set,
   # there's no need to discard these files because it's auto-discarded by the section build file itself.
   if [ -n "$SM_HTMLOUTPUT" ] && [ "$SM_HTMLOUTPUT" = "1" ] ; then
     if [ -z "$SM_AUTOBUILDTEMP" ] ; then
       rm -f $SM_PARENTTMP/$APP.{APP,BUILD,VERSION}
     fi
   fi

   # With SECONDS reset, the shell will add in a fresh value, which we can now use to ascertain the packaging time,
   # by again passing that value as an argument to the runtime function
   SM_PACKAGETIMEA="$SECONDS"
   SM_PACKAGETIMEB="$( runtime $SM_PACKAGETIMEA )"

   # Determine size of SRCDIR aka source directory
   SM_SRCDIRSIZE="$(du -s $SRCDIR | awk '{print $1}')"
   # Determine size of SM_TMP aka build directory size
   SM_BUILDDIRSIZE="$(du -s $SM_TMP | awk '{print $1}')"

   # Calculate SSD write savings if TMPFS has been used
   if [ "$SM_USETMPFS" = "1" ] && \
     [ "$SM_TMPFSENABLEDFORTHISPACKAGE" = "1" ] ; then

     # Determine size of staging directory
     SM_PKGDIRSIZE="$(du -s $PKG | awk '{print $1}')"

     # Sum total of the above two variables is the amount of writes we saved
     SM_TMPFSSAVINGSSUM0="$(( $SM_BUILDDIRSIZE + $SM_PKGDIRSIZE ))"

     # We'll get sum in kB. Convert that to MB.
     SM_TMPFSSAVINGSSUM1="$(echo "scale=2 ; "$SM_TMPFSSAVINGSSUM0" / 1024" | bc)"

     # Store the result for build summary to pickup.
     SM_TMPFSSAVINGSSIZE="$(echo and $SM_TMPFSSAVINGSSUM1"MB" writes to SSD saved)"
   fi

   # Delete the build directory if SM_PRESERVEBUILDDIR is set to 0
   if [ "$SM_PRESERVEBUILDDIR" = "0" ] ; then
     if ! inarray "${SM_TMP}" "${SM_PROTECTEDDIRECTORIES[@]}" ; then
       rm -rf "$SM_TMP"
     else 
       systemdirectorydeletionmessage
       echo "'"$SM_TMP"' IS LISTED AS A PROTECTED DIRECTORY BUT \
ACCIDENTALLY LISTED AS A VALUE FOR "'$SM_TMP'" VARIABLE!! EXITING!!"
       exit 1
     fi
   fi

   # Delete the package build directory if SM_PRESERVEPACKAGEDIR is set to 0
   if [ "$SM_PRESERVEPACKAGEDIR" = "0" ] ; then
     if [[ ! "${SM_PROTECTEDDIRECTORIES[@]}" =~ "${PKG}" ]] ; then
       rm -rf "$PKG"
     else 
       systemdirectorydeletionmessage
       echo "'"$PKG"' IS LISTED AS A PROTECTED DIRECTORY BUT ACCIDENTALLY\
 LISTED AS A VALUE FOR "'$PKG'" VARIABLE!! EXITING!!"
       exit 1
     fi
   fi
}
