#!/bin/sh

set -eu

arcanist_repo='https://github.com/phacility/arcanist.git'
libphutil_repo='https://github.com/phacility/libphutil.git'
phabricator_repo='https://github.com/phacility/phabricator.git'

if [ -z "${1:-}" ]; then
    echo "Usage: $(basename "$0") <version>"
    exit 1
fi

version="$1"

if echo "$version" | grep -q '[a-z][0-9]\{8\}$'; then
    version_ymd="$(
        echo "$version" |
            sed -E 's:^.*([0-9]{4})([0-9]{2})([0-9]{2})$:\1/\2/\3:'
    )"
else
    echo "E: Invalid version number: $version"
    exit 1
fi

udate="$(date --rfc-3339=seconds --date="$version_ymd")"

echo '# Downloading ...'

# Clone to repo at $1 (as of $udate) to $2
download() {
    local url dest
    url="$1"
    dest="$2"

    mkdir -p "$(dirname "$dest")"
    git clone "$url" "$dest"
    (
        cd "$dest"
        git checkout "$(git log -n1 --format=%h --before="$udate")"
    )
}

download "$arcanist_repo" "arcanist-$version"
download "$libphutil_repo" "libphutil-$version"
download "$phabricator_repo" "phabricator-$version/phabricator"

echo '# Copying git revision number...'
(
    cd "phabricator-$version/phabricator"
    echo "based on git revision $(git log -n1 --format=%H)." >conf/local/VERSION
)

echo '# Cleaning up ...'
rm -r -v "arcanist-$version/src/parser/xhpast/bin/xhpast.exe"
rm -r -v "arcanist-$version/bin/arc.bat"
mv \
    "arcanist-$version/support/shell/hooks/bash-completion.sh" \
    "arcanist-$version/support/shell/hooks/arcanist.bash-completion"
chmod -x "arcanist-$version/support/unit/sleep.php"

(
    cd "phabricator-$version/phabricator/"
    rm -r -v \
        externals/wordlist \
        webroot/rsrc/externals/font/fontawesome \
        webroot/rsrc/externals/d3
)

# Remove anything with .git* in $1, print the author time of the last
# commit (in seconds since the epoch).
clean_and_print_at() {
    local dir
    dir="$1"
    (
        cd "$dir"
        at="$(git log -n1 --format=%at)"
        find . -maxdepth 1 -name '.git*' -print0 | xargs -r0 rm -rf
        echo "$at"
    )
}

arcanist_at="$(clean_and_print_at "arcanist-$version")"
libphutil_at="$(clean_and_print_at "libphutil-$version")"
phabricator_at="$(clean_and_print_at "phabricator-$version/phabricator")"

echo '# Packing...'

# Create a reproducible tarball $1 from $2, mtime set to $3.
# Then delete "$dir"
pack() {
    local file dir mtime
    file="$1"
    dir="$2"
    mtime="$3"

    XZ_OPT='-6v' fakeroot tar \
        --sort=name \
        --mtime="@$mtime" \
        -caf "$file" "$dir"
    rm -rf "$dir"
}

pack "phabricator_$version.orig.tar.xz" "phabricator-$version" \
    "$phabricator_at"

pack "phabricator_$version.orig-arcanist.tar.xz" "arcanist-$version" \
    "$arcanist_at"

pack "phabricator_$version.orig-libphutil.tar.xz" "libphutil-$version" \
    "$libphutil_at"
