siebenschlaefer
5/8/2015 - 5:16 PM

update the exercism binary

update the exercism binary

#! /bin/sh

set -eu

BINDIR="$HOME/bin"
DOWNLOADDIR="$HOME/Downloads"
EXECUTABLE="exercism"

os_and_architecture() {
    case `uname -m` in
    x86_64)
        echo "linux-64bit"
        ;;
    i386|i686)
        echo "linux-32bit"
        ;;
    *)
        echo "ERROR: unknown architecture" 2>&1
        return 1
    esac
}

latest_version() {
    # echo "v2.1.0"
    # return 0

    echo "INFO: requesting latest version" >&2
    VERSION=`curl --request HEAD --dump-header - --silent \
        "https://github.com/exercism/cli/releases/latest" \
        | tr -d '\r' \
        | sed -n 's/^Location: \(.*\)/\1/p' \
        | sed -n 's#https://github.com/exercism/cli/releases/tag/\(.*\)#\1#p'`
    echo "INFO: latest version is $VERSION" >&2
    echo "$VERSION"
}

create_dir() {
    DIR="$1"
    if test -d "$DIR"; then
        return 0
    fi
    echo "INFO: creating $DIR" >&2
    mkdir -p "$DIR" || true
    if test ! -d "$DIR"; then
        echo "ERROR: could not create $DIR" >&2
        return 0
    fi
}

download_latest_version() {
    URL="$1"
    FILE="$2"
    if test -e "$FILE"; then
        echo "INFO: $FILE already exists" >&2
        return 0
    fi
    echo "INFO: downloading $FILE" >&2
    curl --location -o "$FILE" "$URL"
}

remove_symlink() {
    DIR="$1"
    FILE="$2"
    echo "INFO: removing old link $DIR/$FILE" >&2
    if test -e "$DIR/$FILE" && test ! -L "$DIR/$FILE"; then
        echo "ERROR: $DIR/$FILE is not a symbolic link"
        return 1
    fi
    test ! -L "$DIR/$FILE" || rm "$DIR/$FILE"
}

extract_file_from_tar() {
    TARFILE="$1"
    DIR="$2"
    FILE="$3"
    echo "INFO: extracting $FILE to $DIR" >&2
    tar xf "$TARFILE" -C "$DIR" "$FILE"
}

replace_file_with_symlink() {
    DIR="$1"
    SYMLINK="$2"
    FILE="$3"
    echo "INFO: versioning $DIR/$SYMLINK as $DIR/$FILE" >&2
    if test ! -e "$DIR/$SYMLINK"; then
        echo "Error: $DIR/$SYMLINK does not exist" >&2
        return 1;
    fi
    if test -L "$DIR/$SYMLINK"; then
        echo "Error: $DIR/$SYMLINK is a symbolic link" >&2
        return 1;
    fi
    mv "$DIR/$SYMLINK" "$DIR/$FILE"
    (cd "$DIR" && ln -s "$FILE" "$SYMLINK")
}

create_dir "$BINDIR"
create_dir "$DOWNLOADDIR"
VERSION=`latest_version`
FLAVOUR=`os_and_architecture`
TARFILE="exercism-${VERSION}-${FLAVOUR}.tgz"
URL="https://github.com/exercism/cli/releases/download/${VERSION}/exercism-${FLAVOUR}.tgz"
download_latest_version "$URL" "$DOWNLOADDIR/$TARFILE"
remove_symlink "$BINDIR" "$EXECUTABLE"
extract_file_from_tar "$DOWNLOADDIR/$TARFILE" "$BINDIR" "$EXECUTABLE"
replace_file_with_symlink "$BINDIR" "$EXECUTABLE" "$EXECUTABLE-$VERSION"

# vim: set sw=4 et: