#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail

function check() {
    if ! command -v "$1" &> /dev/null; then
        echo 'Command `'"$1"'` could not be found. Please install the package providing it.' > /dev/stderr
        return 1
    fi
}

function has() {
  command -v "$1" &> /dev/null
}

check tar
check unxz
check curl
check tail
check cut
check grep
check sed
check tr
check mkdir
check cat

USER=''
PASS=''
BRANCH='master'
CREDS=''

if test -n "$USER"; then
    CREDS="$USER:$PASS@"
fi

if [ -e revng ]; then
    echo "revng folder already exists, aborting"
    exit 1;
fi

mkdir -p revng && cd revng

INITIAL_DOWNLOAD_URL="https://${CREDS}rev.ng/downloads/revng-distributable/$BRANCH.tar.xz"
ACTUAL_DOWNLOAD_URL="$(curl -s -L --head "$INITIAL_DOWNLOAD_URL" | grep -i Location | cut -f2 -d' ' | tail -1 | tr -d '\n\r' | sed "s|//|//${CREDS}|")"
LATEST_TAR_NAME=$(basename "$ACTUAL_DOWNLOAD_URL")

echo "[+] Downloading latest rev.ng release (branch $BRANCH)..."
curl "$ACTUAL_DOWNLOAD_URL" > "$LATEST_TAR_NAME"

echo "[+] Extracting into revng/"
if has pv; then
    pv "$LATEST_TAR_NAME" | tar --extract --xz --strip-components=1 --file -
else
    tar --extract --xz --strip-components=1 --file "$LATEST_TAR_NAME"
fi

rm "$LATEST_TAR_NAME"

TOP_LEVEL_FILES="$(echo * | sed 's/ /", "/g')"
cat > config.json <<EOF
{
  "user": "$USER",
  "pass": "$PASS",
  "branch": "$BRANCH",
  "last-archive": "$LATEST_TAR_NAME",
  "top-level-files": ["$TOP_LEVEL_FILES"]
}
EOF

echo "[+] Done!"
echo '[+] Installation successful in revng/. You can `./revng` from there or take a look at README.md.'
echo '[+] This script is no longer needed, to update just run `./revng update`!'
echo '[+] IMPORTANT: This is a beta release of rev.ng! There will be crashes.'
echo '    Please report problems here: https://discuss.rev.ng/'

