#!/bin/bash
#
# .---.                  .              .
# |                      |              |
# |--- .--. .-.  .-.  .-.|  .-. .--.--. |.-.  .-. .--.  .-.
# |    |   (.-' (.-' (   | (   )|  |  | |   )(   )|  | (.-'
# '    '     --'  --'  -' -  -' '  '   -' -'   -' '   -  --'
#
#                    Freedom in the Cloud
#
# Functions for installing meteor
# See meteor.com
#
# License
# =======
#
# Copyright (C) 2017-2018 Bob Mottram <bob@freedombone.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

METEOR_RELEASE='1.4.4.1'
METEOR_REPO="https://github.com/meteor/meteor"
METEOR_COMMIT='b52c6587d7542c0f27481a3bee8c65be06068ac1'
METEOR_USERACCOUNTS_REPO="git://github.com/meteor-useraccounts/core.git"
METEOR_USERACCOUNTS_COMMIT='2e8986813b51f321f908d2f6211f6f81f76cd627'

function meteor_cleanUp {
    rm -rf "$TARBALL_FILE"
    rm -rf "$INSTALL_TMPDIR"
}

function install_meteor_script {
    meteor_dir=$1

    if [ ! $meteor_dir ]; then
        echo $'No meteor install directory specified'
        exit 692025
    fi

    if [ ! -d $meteor_dir ]; then
        echo $'Meteor install directory not found'
        exit 845382
    fi

    if [[ "$(arch)" == "arm"* ]]; then
        echo 'meteor does not support ARM'
        exit 8362952
    fi
    if [[ "$(arch)" == "i386" || "$(arch)" == "x86_32" ]]; then
        PLATFORM="os.linux.x86_32"
    else
        PLATFORM="os.linux.x86_64"
    fi

    RELEASE="$METEOR_RELEASE"

    DIR_PREFIX="/usr/local"

    TARBALL_URL="$https://meteorinstall-4168.kxcdn.com/packages-bootstrap/${RELEASE}/meteor-bootstrap-${PLATFORM}.tar.gz"
    INSTALL_TMPDIR="$meteor_dir/.meteor-install-tmp"
    TARBALL_FILE="$meteor_dir/.meteor-tarball-tmp"

    # Remove temporary files now in case they exist.
    meteor_cleanUp

    if [ -d $INSTALL_TMPDIR ]; then
        rm -rf $INSTALL_TMPDIR
    fi
    mkdir "$INSTALL_TMPDIR"

    if [ ! -f ${TARBALL_FILE} ]; then
        echo "Downloading Meteor distribution"
        # keep trying to curl the file until it works (resuming where possible)
        MAX_ATTEMPTS=10
        RETRY_DELAY_SECS=5
        set +e
        ATTEMPTS=0
        while [ $ATTEMPTS -lt $MAX_ATTEMPTS ]
        do
            ATTEMPTS=$((ATTEMPTS + 1))

            curl --progress-bar --fail --continue-at - \
                 "$TARBALL_URL" --output "$TARBALL_FILE"

            if [ $? -eq 0 ]
            then
                break
            fi

            echo "Retrying download in $RETRY_DELAY_SECS seconds..."
            sleep $RETRY_DELAY_SECS
        done
    fi

    if [ ! -f ${TARBALL_FILE} ]; then
        echo $'meteor tarball could not be downloaded'
        exit 7272452
    fi

    tar -xzf "$TARBALL_FILE" -C "$INSTALL_TMPDIR" -o

    if [ ! -f ${INSTALL_TMPDIR}/.meteor/meteor ]; then
        echo $'tarball not extracted'
        exit 693252
    fi

    mv "${INSTALL_TMPDIR}/.meteor" "$meteor_dir"

    meteor_cleanUp

    echo ''
    echo "Meteor ${RELEASE} has been installed in $meteor_dir/.meteor"

    METEOR_SYMLINK_TARGET="$(readlink "$meteor_dir/.meteor/meteor")"
    METEOR_TOOL_DIRECTORY="$(dirname "$METEOR_SYMLINK_TARGET")"
    LAUNCHER="$meteor_dir/.meteor/$METEOR_TOOL_DIRECTORY/scripts/admin/launch-meteor"

    if cp "$LAUNCHER" "$DIR_PREFIX/bin/meteor" >/dev/null 2>&1; then
        echo "Writing a launcher script to $DIR_PREFIX/bin/meteor for your convenience."
        cat <<"EOF"

To get started fast:

  $ meteor create ~/my_cool_app
  $ cd ~/my_cool_app
  $ meteor

Or see the docs at:

  docs.meteor.com

EOF
    elif type sudo >/dev/null 2>&1; then
        echo "Writing a launcher script to $DIR_PREFIX/bin/meteor for your convenience."
        echo "This may prompt for your password."

        # New macs (10.9+) don't ship with /usr/local, however it is still in
        # the default PATH. We still install there, we just need to create the
        # directory first.
        # XXX this means that we can run sudo too many times. we should never
        #     run it more than once if it fails the first time
        if [ ! -d "$DIR_PREFIX/bin" ] ; then
            sudo mkdir -m 755 "$DIR_PREFIX" || true
            sudo mkdir -m 755 "$DIR_PREFIX/bin" || true
        fi

        if sudo cp "$LAUNCHER" "$DIR_PREFIX/bin/meteor"; then
            cat <<"EOF"

To get started fast:

  $ meteor create ~/my_cool_app
  $ cd ~/my_cool_app
  $ meteor

Or see the docs at:

  docs.meteor.com

EOF
        else
            cat <<EOF

Couldn't write the launcher script. Please either:

  (1) Run the following as root:
        cp "$LAUNCHER" /usr/bin/meteor
  (2) Add "\$meteor_dir/.meteor" to your path, or
  (3) Rerun this command to try again.

Then to get started, take a look at 'meteor --help' or see the docs at
docs.meteor.com.
EOF
        fi
    else
        cat <<EOF

Now you need to do one of the following:

  (1) Add "\$meteor_dir/.meteor" to your path, or
  (2) Run this command as root:
        cp "$LAUNCHER" /usr/bin/meteor

Then to get started, take a look at 'meteor --help' or see the docs at
docs.meteor.com.
EOF
    fi

}

function install_meteor {
    apt-get -yq install curl
    if [ ! -d $INSTALL_DIR/meteor ]; then
        mkdir $INSTALL_DIR/meteor
    fi
    cd $INSTALL_DIR/meteor
    install_meteor_script
}

function remove_meteor {
    if [ -f /usr/local/bin/meteor ]; then
        rm /usr/local/bin/meteor
    fi
    if [ -f /usr/bin/meteor ]; then
        rm /usr/bin/meteor
    fi
}

# NOTE: deliberately no exit 0
