#!/bin/zsh
# FILE: build.zsh
# USER: Niels Søndergaard
# DATE: 22-02-17
# Build emacs from daily github save
## Derived from https://github.com/renard/emacs-build-macosx
## and
##              https://github.com/mclear-tools/build-emacs-macos
## Patches from https://github.com/d12frosted/homebrew-emacs-plus
## See also https://github.com/jimeh/build-emacs-for-macos

DEBUG=True
## for log 
set -e               # Uncomment `set -e' if you want script to exit
                     # on non-zero status
set -o SH_WORD_SPLIT # for zsh
# ======================================================
# Set Variables
# ======================================================
ROOT_DIR="`pwd`"
CC=/opt/homebrew/bin/gcc
GIT_VERSION=emacs-git-version.el
C=${CC}
SITELISP=/Applications/Emacs.app/Contents/Resources/site-lisp
BREW=$(brew --prefix)
BUILD_DIR=${ROOT_DIR}/emacs-build
SRC_DIR=${ROOT_DIR}/emacs
PATH=

# Add locations to the $PATH that actually exist.
export PATH="./materials:/opt/homebrew/bin:/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin/:${PATH}"
[ -d "/opt/X11/bin" ]  && PATH="/opt/X11/bin:${PATH}"

# save old NEWS
if [ -e NEWS.new ]
  then
    mv NEWS.new NEWS.old
fi



echo "
# ======================================================
# Build emacs 30.0.50
# ======================================================

Building Emacs.app from source"
echo $(date +%H:%M:%S)
if ${DEBUG}
   then
       echo "debug is on"
   else
       echo "debug is off"
fi

echo "
# ======================================================
# Use Homebrew libxml & image libraries
# ======================================================
"
# Check for Homebrew,
if ! command -v brew </dev/null 2>&1
then
   echo "Please install homebrew -- see bemacs-requirements.sh"
   exit -1
else
    echo "Homebrew installed!"
    
fi
# and be sure to have requisites ready

brew bundle --file="./Brewfile"

#
export LDFLAGS="-L${BREW}/opt/jpeg/lib:-L${BREW}/opt/libtiff/lib:-L${BREW}/opt/webp/lib:-L${BREW}/opt/libxml2/lib:-L${BREW}/opt/giflib/lib:-L${BREW}/opt/jpeg/lib:-L${BREW}/opt/libgccjit/lib/gcc/current:${LDFLAGS} " 
export CPPFLAGS="-I${BREW}/opt/jpeg/include:-I${BREW}/opt/libtiff/include:-I${BREW}/opt/cairo/include:-I${BREW}/opt/libxml2/include:-I${BREW}/opt/jpeg/include:-I${BREW}/opt/giflib/include:${CPPFLAGS}"
export PKG_CONFIG_PATH="/opt/homebrew/opt/libxml2/lib/pkgconfig:${PKG_CONFIG_PATH}"
export CXXCFLAGS="-std=c++14"
echo "
# ======================================================
# Use Homebrew libxml pkgconfig
# ======================================================
"
if ${DEBUG}
   then
       env
       echo "
LDFLAGS: ${LDFLAGS}
CPPFLAGS ${CPPFLAGS}
PKG_CONFIG_PATH: ${PKG_CONFIG_PATH}"
fi

echo "
# ======================================================
# Start with a clean build
# ======================================================
"
if [ -e ${BUILD_DIR} ]
  then
    rm -rf ${BUILD_DIR}
fi
mkdir ${BUILD_DIR}
if [ $? -eq 0 ]
  then
    echo $(date +%H:%M:%S) "making the build directory, exited successfully"
    cd "${SRC_DIR}"
  else
    echo "ERROR make clean status exited with error code"
    exit -2
fi


echo "
# ======================================================
# Input for version otherwise default to master
# ======================================================
" 
if test -n "$1"; then
    commit="$1"
else
    commit="origin/master"
    git checkout master 
    git pull 
fi                              
## copy src to build directory
git archive --format tar $commit | tar --directory ${BUILD_DIR} -xf - 

echo "
# ======================================================
# Set variables for git, time, & patches
# ======================================================
"

REV=`git log -n 1 --no-color --pretty='format:%h' ${commit}`
TIMESTAMP=`git log -n 1 --no-color --pretty='format:%at' ${commit}`
PATCH_LIST=`find ${ROOT_DIR}/patches -name '*.patch'`
if ${DEBUG}
   then
       echo "
REV       : ${REV}
TIMESTAMP : ${TIMESTAMP}
PATCH_LIST: ${PATCH_LIST}"
fi
cd ${BUILD_DIR}

 echo "
# ======================================================
# Apply Patches
# ======================================================
"
# Note that this applies all patches in 'patches' dir
for f in ${PATCH_LIST}; do
    echo "Applying patch 'basename $f'"
    /usr/bin/patch -p1 -i $f
done

echo "
# ======================================================
# Info settings
# ======================================================
"
STRINGS="
  nextstep/templates/Emacs.desktop.in
  nextstep/templates/Info-gnustep.plist.in
  nextstep/templates/Info.plist.in
  nextstep/templates/InfoPlist.strings.in
"

DAY=`date -u -r $TIMESTAMP +"%Y-%m-%d"`
ORIG=`grep ^AC_INIT configure.ac`
VNUM=`echo $ORIG | sed 's#^AC_INIT(\(.*\))#\1#; s/ //g' | cut -f2 -d,`
VERS="$DAY Git $REV"
DESCR="macOS_Cocoa_${VNUM}(NiSo)_${DAY}_Git_${REV}"
CFLAGS="-g -O2"
export CC=clang
export OBJC=clang

if ${DEBUG}
   then
       echo "
 DAY:    ${DAY}
 ORIG:   ${ORIG}
 VNUM:   ${VNUM}
 VERS:   ${VERS}
 DESCR:  ${DESCR}
 CFLAGS: ${CFLAGS}"
fi

./autogen.sh

echo "
# ======================================================
# Inscribe Version in Info files
# ======================================================
"
for f in $STRINGS; do
    /usr/bin/sed -e "s/@version@/@version@ $VERS/" -i '' $f
done

echo "
# ======================================================
# Configure emacs
# ======================================================
"
# Here we set config options for emacs For more info see config-options.txt.
# Note that this renames ctags in emacs so that it doesn't conflict with other
# installed ctags; see and don't compress info files, etc
# https://www.topbug.net/blog/2016/11/10/installing-emacs-from-source-avoid-the-conflict-of-ctags/
if ${DEBUG}
   then
       warn='--enable-gcc-warnings=warn-only'
       tyst='--disable-silent-rules'
   else
       warn='--enable-gcc-warnings=no'
       tyst='--silent'
fi
./configure \
    --enable-profiling \
    ${warn} \
    ${tyst} \
    --with-dbus \
    --with-native-compilation \
    --with-ns \
    --with-xwidgets \
    --with-x-toolkit=yes \
    --with-mailutils \
    --with-json \
    --with-jpeg \
    --without-compress-install \
    --program-transform-name='s/^ctags$/emctags/' \


 echo "
# ======================================================
# Build and install everything
# ======================================================
"
## Check number of processors & use as many as we can!
NCPU=$(getconf _NPROCESSORS_ONLN)

## Send output to log file using tee
## See https://stackoverflow.com/a/60432203/6277148
make bootstrap -j$NCPU 2>&1
make install -j$NCPU  2>&1
echo "DONE!"

echo "
# ======================================================
# Move old app & Move new app
# ======================================================
"

if [ -e /Applications/Emacs.app ]
then
    if [ -e /Applications/EmacsOK.app ]
    then
        rm -rf /Applications/EmacsOK.app
    fi
    mv /Applications/Emacs.app /Applications/EmacsOK.app
    echo "Old Emacs.app saved as EmacsOK.app"
fi

echo "Move build to applications folder"
mv ${BUILD_DIR}/nextstep/Emacs.app /Applications
if [ $? -eq 0 ]; then
  echo "               " $(date +%H:%M:%S) " move emacs has been DONE"
else
  echo "ERROR          " $(date +%H:%M:%S) " move emacs exited with error code"
  exit($?)
fi

echo "
# ======================================================
# Record Git SHA
# ======================================================
"
# This records the Git SHA to an elisp file and
# moves it to the site-lisp dir in the emacs build

cp ${ROOT_DIR}/materials/${GIT_VERSION} ${BUILD_DIR}/
sed -e "s/@@GIT_COMMIT@@/$REV/" -i '' ${BUILD_DIR}/${GIT_VERSION}
mv -f ${BUILD_DIR}/${GIT_VERSION} ${SITELISP}/${GIT_VERSION}

echo "DONE!"

echo "
# ======================================================
# Change iconselect 
# ======================================================
"
cp ~/Projects/emacs-icons/modern-pen-3d.icns /Applications/Emacs.app/Contents/Resources/Emacs.icns

echo "DONE!"
echo "
# ======================================================
# Copy C Source Code
# ======================================================
"
# Copy C source files to Emacs
cp -r ${SRC_DIR}/src /Applications/Emacs.app/Contents/Resources/

echo "DONE!"


echo "
# ======================================================
# Cleanup (suspended)
# ======================================================
"

# Deletebuild dir
if ${DEBUG}
then
    echo "DEBUG is on ${BUILD_DIR} remains\n"
else
    rm -rf ${BUILD_DIR}
    echo "DEBUG is off ${BUILD_DIR} is gone\n"
fi

echo "DONE!"

echo "
# ======================================================
# Open new emacs
# ======================================================
"
cd ${ROOT_DIR}
cp -f /Applications/Emacs.app/Contents/Resources/etc/NEWS NEWS.new
diff NEWS.old NEWS.new > NyesteNyt.txt
open /Applications/Emacs.app

echo "Build script finished!"
date
echo $(date +%H:%M:%S)
echo "end of build emacs"

