#!/bin/sh

# The new package will be saved here
PACK_DIR=$(pwd)/darwin/release

# Temp dir for creating *.dmg package
BUILD_PACK_DIR=/var/tmp/doublecmd-$(date +%y.%m.%d)

# Read version number
DC_MAJOR=$(grep 'MajorVersionNr' ../src/doublecmd.lpi | grep -o '[0-9.]\+')
DC_MINOR=$(grep 'MinorVersionNr' ../src/doublecmd.lpi | grep -o '[0-9.]\+' || echo 0)
DC_MICRO=$(grep 'RevisionNr' ../src/doublecmd.lpi | grep -o '[0-9.]\+' || echo 0)
DC_VER=$DC_MAJOR.$DC_MINOR.$DC_MICRO

# Create temp dir for building
BUILD_DC_TMP_DIR=/var/tmp/doublecmd-$DC_VER

# Export from Git
rm -rf $BUILD_DC_TMP_DIR
mkdir $BUILD_DC_TMP_DIR
git -C ../ checkout-index -a -f --prefix=$BUILD_DC_TMP_DIR/

# Save revision number
DC_REVISION=$(linux/update-revision.sh ../ $BUILD_DC_TMP_DIR)

# Set processor architecture
if [ -z $CPU_TARGET ]; then
  export CPU_TARGET=$(fpc -iTP)
fi

export CPU_TARGET=`echo $CPU_TARGET|tr '[:upper:]' '[:lower:]'`

# Set widgetset
if [ -z $lcl ]; then
  export lcl=cocoa
fi

# Set minimal Mac OS X target version
if [ -z $MACOSX_DEPLOYMENT_TARGET ]; then
  if [ $CPU_TARGET = "aarch64" ]; then
    export MACOSX_DEPLOYMENT_TARGET=11.0
  else
    export MACOSX_DEPLOYMENT_TARGET=10.11
  fi
fi

# Copy libraries
cp -a darwin/lib/$CPU_TARGET/*.dylib         $BUILD_DC_TMP_DIR/
cp -a darwin/lib/$CPU_TARGET/$lcl/*.dylib    $BUILD_DC_TMP_DIR/

cd $BUILD_DC_TMP_DIR

# Build all components of Double Commander
./build.sh release

# Update application bundle version
defaults write $(pwd)/doublecmd.app/Contents/Info CFBundleVersion $DC_REVISION
defaults write $(pwd)/doublecmd.app/Contents/Info CFBundleShortVersionString $DC_VER
plutil -convert xml1 $(pwd)/doublecmd.app/Contents/Info.plist
chmod 644 $(pwd)/doublecmd.app/Contents/Info.plist

# Create *.dmg package
mkdir -p $BUILD_PACK_DIR
install/darwin/install.sh $BUILD_PACK_DIR
pushd $BUILD_PACK_DIR
if [ "$lcl" = "qt" ]; then
  macdeployqt doublecmd.app
fi
mv doublecmd.app 'Double Commander.app'
codesign --deep --force --verify --verbose --sign '-' 'Double Commander.app'
popd

install/darwin/create-dmg/create-dmg \
  --volname "Double Commander" \
  --volicon "$BUILD_PACK_DIR/.VolumeIcon.icns" \
  --background "$BUILD_PACK_DIR/.background/bg.jpg" \
  --window-pos 200 200 \
  --window-size 680 366 \
  --text-size 16 \
  --icon-size 128 \
  --icon "Double Commander.app" 110 120 \
  --app-drop-link 360 120 \
  --icon "install.txt" 566 123 \
  --icon ".background" 100 500 \
  "$PACK_DIR/doublecmd-$DC_VER-$DC_REVISION.$lcl.$CPU_TARGET.dmg" \
  "$BUILD_PACK_DIR/"

# Clean DC build dir
rm -rf $BUILD_DC_TMP_DIR
rm -rf $BUILD_PACK_DIR
