#!/bin/sh

# This script installs asciinema cli on your system by downloading a binary
# compatible with your platform and putting it in your $PATH.

{ # Prevent execution if this script was only partially downloaded

set -e

case "$(uname -s).$(uname -m)" in
    Linux.x86_64) platform=linux-amd64;;
    Linux.i?86) platform=linux-386;;
    Linux.armv6l) platform=linux-arm;;
    Linux.armv7l) platform=linux-arm;;
    FreeBSD.amd64) platform=freebsd-amd64;;
    FreeBSD.i386) platform=freebsd-386;;
    Darwin.x86_64) platform=darwin-amd64;;
    Darwin.i?86) platform=darwin-386;;
    *) echo "Sorry, there is no asciinema binary available for your platform. Try building from source." >&2; exit 1;;
esac

version=1.2.0
url="https://github.com/asciinema/asciinema/releases/download/v${version}/asciinema-${version}-${platform}.tar.gz"
bin_name="asciinema"
sudo=""

tmpdir=$(mktemp -d 2>/dev/null || mktemp -d -t 'asciinema-tmp')
trap 'rm -rf $tmpdir' EXIT

echo "Downloading asciinema v${version} for $platform..."
curl -L --progress-bar "$url" | tar xz -C $tmpdir

if [ -d "$HOME/bin" ]; then
    if echo ":$PATH:" | grep -q ":~/bin:" || echo ":$PATH:" | grep -q ":$HOME/bin:"; then
        target="$HOME/bin/$bin_name"
    fi
elif [ -d "/usr/local/bin" ]; then
    if echo ":$PATH:" | grep -q ":/usr/local/bin:"; then
        target="/usr/local/bin/$bin_name"
        if [ ! -w /usr/local/bin ]; then
            sudo=sudo
            echo "Warning: you may be asked for administrator password to save the file in /usr/local/bin directory"
        fi
    fi
fi

if [ -z "$target" ]; then
    target="$PWD/$bin_name"
    echo "Warning: couldn't find ~/bin or /usr/local/bin in your \$PATH"
fi

echo "Installing to $target..."
if $sudo cp $tmpdir/asciinema*/asciinema $target; then
    $sudo chmod a+x $target
    echo "Success."
    echo
    echo "Start recording your terminal by running: asciinema rec"
else
    echo "Error: couldn't copy $bin_name to $target"
fi

} # End of wrapping
