#!/bin/sh
set -eu

VERSION="0.4.1"
BASE_URL="https://ipbind.sh"
RELEASE_URL="$BASE_URL/releases/$VERSION"

INSTALL_DIR="${IPBIND_INSTALL_DIR:-/usr/local/bin}"
INSTALL_PATH="$INSTALL_DIR/ipbind"

die() {
    printf 'ipbind installer: %s\n' "$*" >&2
    exit 1
}

command -v curl >/dev/null 2>&1 ||
    die "curl is required"

command -v sha256sum >/dev/null 2>&1 ||
    die "sha256sum is required"

[ "$(uname -s)" = "Linux" ] ||
    die "automatic installation currently supports Linux only"

tmpdir=$(mktemp -d)

cleanup() {
    rm -rf "$tmpdir"
}

trap cleanup EXIT HUP INT TERM

printf '\nipbind.sh\n'
printf 'Installing v%s...\n\n' "$VERSION"

curl -fsSL \
    "$RELEASE_URL/ipbind" \
    -o "$tmpdir/ipbind" ||
    die "could not download ipbind"

curl -fsSL \
    "$RELEASE_URL/ipbind.sha256" \
    -o "$tmpdir/ipbind.sha256" ||
    die "could not download checksum"

expected=$(
    awk 'NR == 1 { print $1 }' "$tmpdir/ipbind.sha256"
)

actual=$(
    sha256sum "$tmpdir/ipbind" |
    awk '{ print $1 }'
)

[ -n "$expected" ] ||
    die "invalid checksum file"

if [ "$actual" != "$expected" ]; then
    die "checksum verification failed"
fi

sh -n "$tmpdir/ipbind" ||
    die "downloaded client failed shell validation"

chmod 755 "$tmpdir/ipbind"

install_client() {
    cp "$tmpdir/ipbind" "$INSTALL_PATH"
    chmod 755 "$INSTALL_PATH"
}

if [ "$(id -u)" -eq 0 ]; then

    mkdir -p "$INSTALL_DIR"
    install_client

elif mkdir -p "$INSTALL_DIR" 2>/dev/null; then

    if [ -w "$INSTALL_DIR" ]; then
        install_client
    elif command -v sudo >/dev/null 2>&1; then
        sudo cp "$tmpdir/ipbind" "$INSTALL_PATH"
        sudo chmod 755 "$INSTALL_PATH"
    else
        printf '\n'
        printf 'Root access is required to install to:\n'
        printf '  %s\n\n' "$INSTALL_PATH"
        printf 'Run this installer as root, or install the client manually.\n'
        exit 1
    fi

elif command -v sudo >/dev/null 2>&1; then

    sudo mkdir -p "$INSTALL_DIR"
    sudo cp "$tmpdir/ipbind" "$INSTALL_PATH"
    sudo chmod 755 "$INSTALL_PATH"

else

    printf '\n'
    printf 'Root access is required to install to:\n'
    printf '  %s\n\n' "$INSTALL_PATH"
    printf 'Run this installer as root, or install the client manually.\n'
    exit 1

fi

printf 'Checksum: OK\n'
printf 'Installed: %s\n\n' "$INSTALL_PATH"

"$INSTALL_PATH" version

printf '\nGet started:\n\n'
printf '  ipbind claim home\n'
printf '  ipbind enable\n\n'
