#!/bin/sh
#
# mimifetch - tiny system info. Installer.
#
#   one-liner: curl -fsSL https://mimifetch.themaster2009sf.ru/install.sh | sh
#   from repo: sh install.sh
#
#   env overrides: MIMIFETCH_BASE=<mirror url> DESTDIR=<staging> PREFIX=<prefix>
#

set -e

BASE="${MIMIFETCH_BASE:-https://mimifetch.themaster2009sf.ru}"
PREFIX="${PREFIX:-/usr/local}"
DESTDIR="${DESTDIR:-}"
BINDIR="${DESTDIR}${PREFIX}/bin"

log() { printf '==> %s\n' "$*"; }
die() { printf 'mimifetch: %s\n' "$*" >&2; exit 1; }

# ---- environment checks -------------------------------------------
[ "$(uname -s)" = "Linux" ] ||
    die "auto-install supports Linux only (download the sources to port manually)"
command -v gcc >/dev/null 2>&1 ||
    die "'gcc' not found. Install a compiler:  apt install gcc  |  pacman -S gcc  |  dnf install gcc"
{ command -v curl >/dev/null 2>&1 || command -v wget >/dev/null 2>&1; } ||
    die "'curl' or 'wget' not found"
command -v sha256sum >/dev/null 2>&1 ||
    die "'sha256sum' not found (coreutils)"

tmp=$(mktemp -d) || die "failed to create temp dir"
trap 'rm -rf "$tmp"' EXIT INT TERM

# ---- fetch ---------------------------------------------------------
fetch() {
    if command -v curl >/dev/null 2>&1; then
        curl -fsSL "$1" -o "$2"
    else
        wget -q "$1" -O "$2"
    fi
}

log "downloading sources"
fetch "$BASE/mimifetch.c"        "$tmp/mimifetch.c"
fetch "$BASE/mimifetch.c.sha256" "$tmp/mimifetch.c.sha256"

log "verifying checksum"
( cd "$tmp" && sha256sum --check mimifetch.c.sha256 ) ||
    die "checksum mismatch - download corrupted"

# ---- build & install -----------------------------------------------
log "building"
gcc "$tmp/mimifetch.c" -O2 -Wall -Wextra -o "$tmp/mimifetch"

log "installing to $BINDIR"
mkdir -p "$BINDIR"
install -m 0755 "$tmp/mimifetch" "$BINDIR/mimifetch"

log "done. run: mimifetch"