#!/usr/bin/env bash
# First installation from a published Weft release. Keep the call to main last:
# when piped into Bash, no installation starts while functions are still arriving.
set -euo pipefail

readonly RELEASES_URL='https://gitlab.com/mathias.ewald/weft/-/releases'

die() { printf 'weft-install: %s\n' "$*" >&2; exit 1; }

usage() {
    cat <<'EOF'
Usage: bash install.sh [--method systemd|docker] [--role consumer|provider] [--version vX.Y.Z] [--compose-dir DIR]
--compose-dir selects the new directory for compose.yaml. Relative paths start in
your current directory. Defaults: ~/weft/client (consumer), ~/weft/server (provider).
With a terminal, missing choices are prompted. For unattended installation:
  curl -fsSL https://weftai.eu/install.sh | bash -s -- --method systemd --role consumer
  curl -fsSL https://weftai.eu/install.sh | bash -s -- --method docker --role provider --compose-dir "$HOME/services/weft"
EOF
}

choose() {
    local answer
    if ! { exec 3<>/dev/tty; } 2>/dev/null; then
        usage >&2
        die "No terminal; supply both --method and --role."
    fi
    while true; do
        printf '%s: 1) %s  2) %s: ' "$1" "$2" "$3" >&3
        IFS= read -r answer <&3 || die "Installation cancelled."
        case $answer in
            1|"$2") printf '%s' "$2"; return ;;
            2|"$3") printf '%s' "$3"; return ;;
        esac
    done
}

require_absent() {
    local update_hint=$1 path
    shift
    for path in "$@"; do
        [[ ! -e $path && ! -L $path ]] || die "Found $path. $update_hint"
    done
}

fetch() {
    curl --proto '=https' --proto-redir '=https' -fsSL --connect-timeout 15 --max-time 180 "$@"
}

resolve_version() {
    local version=$1 latest
    if [[ -z $version ]]; then
        latest=$(fetch --head --output /dev/null --write-out '%{url_effective}' "$RELEASES_URL/permalink/latest") || return
        version=${latest##*/}
    fi
    [[ $version =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "Expected a release tag of the form vX.Y.Z."
    printf '%s\n' "$version"
}

download_archive() {
    local version=$1 archive=$2 digest
    digest=$(awk -v name="$archive" '$2 == name {print $1; n++} END {exit n != 1}' SHA256SUMS) ||
        die "Expected one checksum for $archive in $version."
    [[ $digest =~ ^[[:xdigit:]]{64}$ ]] || die "Invalid checksum for $archive."
    fetch "$RELEASES_URL/$version/downloads/$archive" > "$archive"
    printf '%s  %s\n' "$digest" "$archive" | sha256sum -c -
}

stage_release() {
    local version=$1 archive=$2 stage cleanup
    stage=$(mktemp -d)
    CDPATH= cd -P -- "$stage"
    # Pin cleanup to this directory even after Compose changes directory.
    printf -v cleanup 'rm -rf -- %q' "$PWD"
    trap "$cleanup" EXIT
    fetch "$RELEASES_URL/$version/downloads/SHA256SUMS" > SHA256SUMS
    download_archive "$version" "$archive"
}

wait_for_info() {
    local deadline=$((SECONDS + 30))
    until "$@" info </dev/null 2>/dev/null; do
        if (( SECONDS >= deadline )); then
            "$@" info </dev/null
            return
        fi
        sleep 1
    done
}

prepare_systemd() (
    local config_file=$1 bin=$2 unit=$3 config=$4
    local created=() pending=''
    install_native_file() {
        local src=$1 dest=$2 mode=$3
        pending=$(mktemp "${dest}.XXXXXXXX")
        install -m "$mode" "$src" "$pending"
        ln -T "$pending" "$dest"
        created+=("$dest")
        rm "$pending"
        pending=''
    }
    mkdir -p "$bin" "${unit%/*}" "${config%/*}"
    # Claim this fresh configuration before installing any files; two installers
    # for the same user cannot both proceed.
    mkdir -m 700 "$config"
    trap 'rm -f -- ${pending:+"$pending"} "${created[@]}"; rmdir "$config"' EXIT
    install_native_file weft "$bin/weft" 755
    install_native_file weftd "$bin/weftd" 755
    install_native_file weftd.service "$unit" 644
    install_native_file "$config_file" "$config/config.yaml" 600
    trap - EXIT
)

install_systemd() (
    local role=$1 directory=$2 version=$3 compose_dir=$4
    [[ -z $compose_dir ]] || die "--compose-dir only applies to Docker Compose."
    local bin="$HOME/.local/bin" unit="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/weftd.service"
    local config="$HOME/.config/weft" state="${XDG_STATE_HOME:-$HOME/.local/state}/weft"
    local update_hint='For an existing systemd install, use weft update.' load
    [[ $unit == /* && $state == /* ]] || die "XDG paths must be absolute."
    (( EUID != 0 )) || die "Run the systemd installation as your normal login user."
    systemctl --user show-environment >/dev/null || die "A running systemd user manager is required."
    require_absent "$update_hint" "$bin/weft" "$bin/weftd" "$unit" "$unit.d" "$config" "$state"
    load=$(systemctl --user show weftd.service --property=LoadState --value)
    [[ $load == not-found ]] || die "Found a weftd.service unit ($load). $update_hint"

    local archive=weft-linux-amd64.tar.gz
    version=$(resolve_version "$version")
    printf 'Installing Weft %s: %s via systemd in %s\n' "$version" "$role" "$bin"
    stage_release "$version" "$archive"
    local config_archive=$archive
    tar -xzf "$archive" weft weftd weftd.service
    # These systemd releases shipped the client example only in the Compose bundle.
    if [[ $role == consumer && $version == v0.1.[3-9] ]]; then
        config_archive=weft-compose.tar.gz
        download_archive "$version" "$config_archive"
    fi
    tar -xzf "$config_archive" "$directory/config.yaml"
    ./weft --version
    ./weftd --version
    prepare_systemd "$directory/config.yaml" "$bin" "$unit" "$config"
    printf 'Service: %s (logs: journalctl --user -u weftd.service)\n' "$unit"
    systemctl --user daemon-reload
    systemctl --user enable --now weftd.service
    wait_for_info "$bin/weft"
    printf 'Check your node: %q info\n' "$bin/weft"
)

install_docker() (
    local role=$1 directory=$2 version=$3 compose_dir=$4 guided=$5
    local default_dir="$HOME/weft/$directory" destination
    if $guided && [[ -z $compose_dir ]]; then
        {
            printf 'New Compose project directory [%s]: ' "$default_dir" >&3
            IFS= read -r compose_dir <&3 || die "Installation cancelled."
        } 3<>/dev/tty
    fi
    # Resolve paths before changing into the temporary download directory.
    destination=${compose_dir:-$default_dir}
    case $destination in
        \~) destination=$HOME ;;
        \~/*) destination="$HOME/${destination#\~/}" ;;
        /*) ;;
        *) destination="$PWD/$destination" ;;
    esac
    while [[ $destination == */ && $destination != / ]]; do
        destination=${destination%/}
    done

    local update_hint='Follow the Docker Compose update instructions in https://weftai.eu/docs/manage/update/.'
    [[ -z ${COMPOSE_PROJECT_NAME:-}${COMPOSE_FILE:-}${WEFT_IMAGE:-} ]] ||
        die "Unset COMPOSE_PROJECT_NAME, COMPOSE_FILE and WEFT_IMAGE to use the released project."
    docker compose version >/dev/null || die "Install Docker Engine and the Docker Compose plugin first."
    docker info >/dev/null || die "Cannot connect to the Docker engine as this user."
    require_absent "$update_hint" "$destination"
    # The bundle names its project explicitly, so an installation elsewhere
    # (or a stopped project with only its identity volume left) can conflict.
    local label="label=com.docker.compose.project=weft-$role" containers volumes
    containers=$(docker ps -aq --filter "$label")
    volumes=$(docker volume ls -q --filter "$label")
    [[ -z $containers && -z $volumes ]] || die "Found Docker project weft-$role. $update_hint"

    local archive=weft-compose.tar.gz
    version=$(resolve_version "$version")
    printf 'Installing Weft %s: %s via docker in %s\n' "$version" "$role" "$destination"
    stage_release "$version" "$archive"
    tar -xzpf "$archive" "$directory"
    mkdir -p "$(dirname -- "$destination")"
    mkdir "$destination"
    if ! cp -Rp "$directory/." "$destination/"; then
        rm -rf -- "$destination"
        die "Could not copy the release project to $destination."
    fi
    cd "$destination"
    printf 'Project: %s (logs: docker compose logs)\n' "$destination"
    docker compose up -d
    wait_for_info docker compose exec -T weft weft
    printf 'Check your node: cd %q && docker compose exec weft weft info\n' "$destination"
)

main() {
    local method='' role='' version='' compose_dir='' guided=false directory
    while (( $# )); do
        case $1 in
            --help|-h) usage; return ;;
            --method) method=${2:?--method requires systemd or docker} ;;
            --role) role=${2:?--role requires consumer or provider} ;;
            --version) version=${2:?--version requires a vX.Y.Z tag} ;;
            --compose-dir) compose_dir=${2:?--compose-dir requires a project directory} ;;
            *) usage >&2; die "Unknown argument: $1" ;;
        esac
        shift 2
    done
    [[ $(uname -s) == Linux && $(uname -m) == x86_64 ]] || die "Weft releases support Linux x86-64."
    [[ ${HOME:-} == /* ]] || die "An absolute HOME is required."
    if [[ -z $method || -z $role ]]; then
        guided=true
        [[ -n $method ]] || method=$(choose 'Installation method' systemd docker)
        [[ -n $role ]] || role=$(choose 'Node role' consumer provider)
    fi
    case $role in
        consumer) directory=client ;;
        provider) directory=server ;;
        *) die "Choose --role consumer or provider." ;;
    esac
    case $method in
        systemd) install_systemd "$role" "$directory" "$version" "$compose_dir" ;;
        docker) install_docker "$role" "$directory" "$version" "$compose_dir" "$guided" ;;
        *) die "Choose --method systemd or docker." ;;
    esac
}

main "$@"
