#!/bin/sh

main() {
    if ! command -v node >/dev/null 2>&1; then
        printf '%s\n' 'dinocode: Node.js 22 or newer is required. Install Node.js and npm, then retry.' >&2
        return 1
    fi

    if ! node_version=$(node --version); then
        printf '%s\n' 'dinocode: Could not determine the Node.js version.' >&2
        return 1
    fi
    node_major=${node_version#v}
    node_major=${node_major%%.*}
    case "$node_major" in
        ''|*[!0-9]*)
            printf '%s\n' 'dinocode: Could not determine the Node.js major version.' >&2
            return 1
            ;;
    esac
    if ! [ "$node_major" -ge 22 ] 2>/dev/null; then
        printf 'dinocode: Node.js 22 or newer is required (found %s).\n' "$node_version" >&2
        return 1
    fi

    if ! command -v npm >/dev/null 2>&1; then
        printf '%s\n' 'dinocode: npm is required. Install npm, then retry.' >&2
        return 1
    fi

    version=${DINOCODE_VERSION-latest}
    if ! node -e '
        const version = process.argv[1];
        const pattern = /^(?:latest|[0-9]+(?:\.[0-9]+){0,2}(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)$/;
        const match = version.match(pattern);
        process.exit(match && match[0] === version ? 0 : 1);
    ' -- "$version"; then
        printf '%s\n' 'dinocode: DINOCODE_VERSION must be latest or a numeric-leading package version (for example, 1.2.3 or 1.2.3-beta.1).' >&2
        return 1
    fi

    if [ -z "${DINOCODE_INSTALL_PREFIX:-}" ] && [ -z "${HOME:-}" ]; then
        printf '%s\n' 'dinocode: Set HOME or an absolute DINOCODE_INSTALL_PREFIX.' >&2
        return 1
    fi
    prefix=${DINOCODE_INSTALL_PREFIX:-"$HOME/.local"}
    case "$prefix" in
        /*) ;;
        *)
            printf '%s\n' 'dinocode: DINOCODE_INSTALL_PREFIX must be an absolute path.' >&2
            return 1
            ;;
    esac

    printf 'Installing dinocode@%s in %s...\n' "$version" "$prefix"
    if ! npm install --global --prefix "$prefix" -- "dinocode@$version"; then
        printf '%s\n' 'dinocode: npm installation failed. Check the npm output above and that the prefix is writable by your user.' >&2
        return 1
    fi

    printf 'Installed dinocode@%s.\n' "$version"
    printf '%s\n' 'To make the dinocode command available, run this in your shell:'
    printf '%s' "  export PATH='"
    path_remaining=$prefix/bin
    while :; do
        case "$path_remaining" in
            *"'"*)
                printf '%s' "${path_remaining%%"'"*}" "'\\''"
                path_remaining=${path_remaining#*"'"}
                ;;
            *)
                printf '%s' "$path_remaining"
                break
                ;;
        esac
    done
    printf '%s\n' "':\"\$PATH\""
    printf '%s\n' 'No shell profiles were modified.'
}

# Keep execution last so an incomplete download cannot run a partial installer.
main
