#!/bin/sh
# Alpine Linux pre-install script for linux-patch-api
# Runs before package files are laid down
# Matches Debian preinst behavior: create directories, set permissions

# Create required directories
mkdir -p /etc/linux_patch_api/certs
mkdir -p /var/lib/linux_patch_api
mkdir -p /var/log/linux_patch_api

# Generate machine-id if not present (required for enrollment)
# Alpine Linux does not include /etc/machine-id by default
if [ ! -f /etc/machine-id ] || [ ! -s /etc/machine-id ]; then
    if command -v uuidgen > /dev/null 2>&1; then
        uuidgen | tr -d '-' > /etc/machine-id
    elif [ -f /proc/sys/kernel/random/uuid ]; then
        cat /proc/sys/kernel/random/uuid | tr -d '-' > /etc/machine-id
    else
        # Fallback: generate from /dev/urandom
        od -x -N4 /dev/urandom | head -1 | awk '{print $2$3}' > /etc/machine-id
    fi
    chmod 444 /etc/machine-id
fi

# Set proper ownership (service runs as root)
chown -R root:root /var/lib/linux_patch_api
chown -R root:root /var/log/linux_patch_api

# Set secure permissions
chmod 750 /etc/linux_patch_api
chmod 750 /etc/linux_patch_api/certs
chmod 755 /var/lib/linux_patch_api
chmod 755 /var/log/linux_patch_api
