#!/usr/bin/env bash
# Build and install a minimal framebuffer Hello World app and APPLaunch entry.
# Run as your normal user; sudo is used only to install into system directories.
set -euo pipefail

APP_DIR=/usr/share/APPLaunch/applications
APP_BIN=/usr/local/bin/hello-world-fb

if [[ ! -d "$APP_DIR" ]]; then
  echo "APPLaunch applications directory not found: $APP_DIR" >&2
  exit 1
fi
if ! command -v cc >/dev/null 2>&1; then
  echo "A C compiler (cc) is required; install one and rerun." >&2
  exit 1
fi

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT

cat > "$work/hello-world-fb.c" <<'C_SOURCE'
#include <errno.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>

/* Five-column, seven-row glyphs. */
static const uint8_t glyphs[][7] = {
    {17,17,17,31,17,17,17}, /* H */
    {31,16,16,30,16,16,31}, /* E */
    {16,16,16,16,16,16,31}, /* L */
    {14,17,17,17,17,17,14}, /* O */
    {17,17,17,21,21,21,10}, /* W */
    {30,17,17,30,20,18,17}, /* R */
    {30,17,17,17,17,17,30}, /* D */
    {0,0,0,0,0,0,0}          /* space */
};
static const uint8_t *get_glyph(char c) {
    switch (c) {
    case 'H': return glyphs[0]; case 'E': return glyphs[1];
    case 'L': return glyphs[2]; case 'O': return glyphs[3];
    case 'W': return glyphs[4]; case 'R': return glyphs[5];
    case 'D': return glyphs[6]; default: return glyphs[7];
    }
}
static unsigned long channel(unsigned v, struct fb_bitfield f) {
    if (!f.length) return 0;
    unsigned long max = (1UL << f.length) - 1;
    return ((v * max / 255UL) << f.offset);
}
static void put_pixel(volatile unsigned char *fb, const struct fb_fix_screeninfo *fix,
                     const struct fb_var_screeninfo *var, unsigned bytes,
                     unsigned x, unsigned y, unsigned r, unsigned g, unsigned b) {
    size_t off = (size_t)(y + var->yoffset) * fix->line_length +
                 (size_t)(x + var->xoffset) * bytes;
    unsigned long px = channel(r, var->red) | channel(g, var->green) |
                       channel(b, var->blue);
    for (unsigned i = 0; i < bytes; i++) fb[off + i] = (unsigned char)(px >> (8 * i));
}
int main(void) {
    const char *paths[] = {"/dev/fb_lcd", "/dev/fb0"};
    int fd = -1; const char *dev = NULL;
    for (unsigned i = 0; i < sizeof(paths)/sizeof(paths[0]); i++) {
        fd = open(paths[i], O_RDWR | O_CLOEXEC);
        if (fd >= 0) { dev = paths[i]; break; }
    }
    if (fd < 0) { fprintf(stderr, "Cannot open LCD framebuffer: %s\n", strerror(errno)); return 2; }
    struct fb_fix_screeninfo fix; struct fb_var_screeninfo var;
    if (ioctl(fd, FBIOGET_FSCREENINFO, &fix) < 0 || ioctl(fd, FBIOGET_VSCREENINFO, &var) < 0) {
        fprintf(stderr, "Cannot read framebuffer mode: %s\n", strerror(errno)); close(fd); return 3;
    }
    unsigned bytes = (var.bits_per_pixel + 7) / 8;
    if (var.grayscale || bytes < 2 || bytes > 4 || var.xres < 80 || var.yres < 40) {
        fprintf(stderr, "Unsupported framebuffer mode: %ux%u, %u bpp\n", var.xres, var.yres, var.bits_per_pixel);
        close(fd); return 4;
    }
    size_t maplen = fix.smem_len;
    volatile unsigned char *fb = mmap(NULL, maplen, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    if (fb == MAP_FAILED) { fprintf(stderr, "Cannot map %s: %s\n", dev, strerror(errno)); close(fd); return 5; }

    /* Fill background and draw centered text. This temporarily replaces the framebuffer contents. */
    for (unsigned y = 0; y < var.yres; y++)
        for (unsigned x = 0; x < var.xres; x++) put_pixel(fb, &fix, &var, bytes, x, y, 8, 22, 48);
    const char *text = "HELLO WORLD";
    const unsigned scale = 4, advance = 28;
    int sx = ((int)var.xres - (int)strlen(text) * (int)advance + (int)scale) / 2;
    int sy = ((int)var.yres - 7 * (int)scale) / 2;
    for (unsigned i = 0; text[i]; i++) {
        const uint8_t *ch = get_glyph(text[i]);
        for (unsigned row = 0; row < 7; row++) for (unsigned col = 0; col < 5; col++) {
            if (!(ch[row] & (1u << (4-col)))) continue;
            for (unsigned dy = 0; dy < scale; dy++) for (unsigned dx = 0; dx < scale; dx++) {
                int x = sx + (int)i*(int)advance + (int)col*(int)scale + (int)dx;
                int y = sy + (int)row*(int)scale + (int)dy;
                if (x >= 0 && y >= 0 && x < (int)var.xres && y < (int)var.yres)
                    put_pixel(fb, &fix, &var, bytes, (unsigned)x, (unsigned)y, 255, 255, 255);
            }
        }
    }
    (void)msync((void *)fb, maplen, MS_SYNC);
    fprintf(stderr, "Displayed HELLO WORLD on %s for 8 seconds.\n", dev);
    sleep(8);
    munmap((void *)fb, maplen); close(fd); return 0;
}
C_SOURCE

cc -O2 -Wall -Wextra -o "$work/hello-world-fb" "$work/hello-world-fb.c"
cat > "$work/hello-world.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=Hello World
Comment=Framebuffer Hello World test
Exec=$APP_BIN
Terminal=false
EOF

# Installation requires administrator privileges. The app writes directly to the
# LCD framebuffer when launched and temporarily replaces its current contents.
sudo install -o root -g root -m 0755 "$work/hello-world-fb" "$APP_BIN"
sudo install -o root -g root -m 0644 "$work/hello-world.desktop" "$APP_DIR/hello-world.desktop"
echo "Installed app binary and launcher entry. Select Hello World in APPLaunch to test it."
echo "This script does not reboot, restart APPLaunch, or verify that the launcher reloads its app list."
