#!/bin/bash

version="0.5.1"

name="julia-${version}"

src="${name}.tar.gz"

url="https://github.com/JuliaLang/julia/releases/download/v${version}/${name}.tar.gz"

sha512="7036ff566b7a4c37d693cce3706446219d3fdc9aac9cb059d85a4c5f8b65d881ff541000c2f807812fc62020be6a46e65660baa621d0b243accb14039f6331a8"

test_dir_base=$1/julia_test_

# Get unique name for work directory.
test_dir=$(mktemp -d "${test_dir_base}.XXXXXXXX")

build_dir=$test_dir/build

install_dir=$test_dir/install

stage_dir=$test_dir/stage

src_dir=$build_dir/$name

current_dir=`pwd`

# Make sure the necessary directories exist.
mkdir -p $build_dir $install_dir $stage_dir $src_dir

cd $build_dir

# Download the source code.
wget -O $src $url

# Check the download's sha512sum.
if [ "$sha512" != "`sha512sum $src | cut -d " " -f 1`" ]

  then

  echo -e "\nError! Could not verify authenticity of downloaded source code!\n"

  cd $current_dir
  
  return 1 2> /dev/null || exit 1
  
fi   
  
# Extract the source code.  
tar -xzvf $src -C $src_dir --strip-components=1

cd $src_dir

# Compilation fails unless we explicitly link against stdc++.
# TODO: Why is this the case? 
cxxflags_="$CXXFLAGS -lstdc++"   

# Compile. 
CXXFLAGS=$cxxflags_ make prefix=$install_dir MARCH=native -j 13 

# Install at the fake root.
CXXFLAGS=$cxxflags_ make DESTDIR=$stage_dir prefix=$install_dir -j 13 install

unset $cxxflags_

# Make package.  
cd $stage_dir

tar -czvf ${current_dir}/${name}.pkg.tar.gz .

cd $current_dir
