#!/usr/bin/env bash

# Original package: https://github.com/timsutton/osx-vm-templates

# This script will use the setup in this package to create a virtual image for
# macOS following the specifications on its header.

if [[ "$#" == "0" ]]; then
	echo "usage: $0 <macos-version>"
	echo "example: $0 10.9"
	exit 1
fi

# Edit this part and modify it as you see fit
username=gitlab
password=gitlab
curdir=`pwd`
outdir="${curdir}/images"
boxdir="${curdir}/boxes"

# Expected app and image names (cannot really guess - wait for outputs and set
# as appropriate)
if [[ "$1" == "10.9" ]]; then
	app="/Applications/Install OS X Mavericks.app"
	image="${outdir}/OSX_InstallESD_10.9.5_13F34.dmg"
  guest_os_type="MacOS109_64"
  machine_name="macos109"
  xcode_sdk_version="109"
else
	echo "Version $1 is currently unsupported"
	exit 1
fi

echo "Checking for Xcode installer and SDK availability..."
if [ ! -r "xcode/XcodeLegacy.sh" ]; then
  echo "XcodeLegacy.sh not available at directory xcode/"
  echo "Download it from here: https://github.com/devernay/xcodelegacy"
  exit 1
elif [ ! -r "xcode/Xcode${xcode_sdk_version}SDK.tar.gz" ]; then
  echo "SDK not available at xcode/Xcode${xcode_sdk_version}SDK.tar.gz"
  echo "Use XcodeLegacy.sh (https://github.com/devernay/xcodelegacy)"
  echo " - and generate it before running the image build, e.g.:..."
  echo "$ ./XcodeLegacy.sh -osx${xcode_sdk_version} buildpackages"
  echo "You'll also need the original Xcode DMG for this"
  echo " - check the URL above for links"
  exit 1
fi

echo "Building virtualbox machine for macOS $1..."
echo "username = ${username}"
echo "password = ${password}"
echo "out dir. = ${outdir}"
echo "app      = ${app}"
echo "image    = ${image}"
echo "os type  = ${guest_os_type}"
echo "name     = ${machine_name}"
echo "sdk vers.= ${xcode_sdk_version}"

if [ ! -r "${image}" ]; then
	sudo prepare_iso/prepare_iso.sh \
		-u ${username} \
		-p ${password} \
		-i prepare_iso/support/gitlab.jpg \
		-D DISABLE_REMOTE_MANAGEMENT \
		"${image}" "${outdir}"
fi

#-var update_system=0 \
cd packer && \
packer build \
  -debug \
  -on-error=ask \
  -only virtualbox-iso \
  -var iso_url="${image}" \
  -var output_directory="${boxdir}" \
  -var guest_os_type="${guest_os_type}" \
  -var machine_name="${machine_name}" \
  -var xcode_sdk_version="${xcode_sdk_version}" \
  -var username="${username}" \
  -var password="${password}" \
  -var provisioning_delay=30 \
  template.json
