#!/bin/bash
# Post-installation script for rpi-power-hat

# Don't exit on errors to prevent installation failure
# set -e

# Create necessary directories
echo "Creating rpi-power-hat data directories..."
mkdir -p /var/lib/rpi-power-hat/images
mkdir -p /var/lib/rpi-power-hat/logs
# working/firstrun no longer used; temporary firstrun scripts are created under /tmp
mkdir -p /var/lib/rpi-power-hat/keys
mkdir -p /var/lib/rpi-power-hat/history
mkdir -p /var/log/rpi-power-hat
mkdir -p /etc/rpi-power-hat

# Check if gpio group exists, create if not
if ! getent group gpio > /dev/null 2>&1; then
    echo "Creating gpio group..."
    groupadd gpio || echo "Warning: Failed to create gpio group (may already exist)"
fi

# Check if i2c group exists, create if not  
if ! getent group i2c > /dev/null 2>&1; then
    echo "Creating i2c group..."
    groupadd i2c || echo "Warning: Failed to create i2c group (may already exist)"
fi

# Set proper ownership and permissions (only if groups exist)
if getent group gpio > /dev/null 2>&1; then
    chown -R root:gpio /var/lib/rpi-power-hat 2>/dev/null || echo "Warning: Could not set ownership on /var/lib/rpi-power-hat"
    chmod -R 775 /var/lib/rpi-power-hat 2>/dev/null || echo "Warning: Could not set permissions on /var/lib/rpi-power-hat"
    chown -R root:gpio /var/log/rpi-power-hat 2>/dev/null || echo "Warning: Could not set ownership on /var/log/rpi-power-hat"
    chmod -R 775 /var/log/rpi-power-hat 2>/dev/null || echo "Warning: Could not set permissions on /var/log/rpi-power-hat"
    # Allow gpio group to write temp files beside configs in /etc/rpi-power-hat (for sed -i)
    chown root:gpio /etc/rpi-power-hat 2>/dev/null || echo "Warning: Could not set ownership on /etc/rpi-power-hat"
    chmod 2775 /etc/rpi-power-hat 2>/dev/null || echo "Warning: Could not set permissions on /etc/rpi-power-hat"
fi

# Ensure configuration files have correct permissions (only if they exist)
if [ -f /etc/rpi-power-hat/hardware.conf ] && getent group gpio > /dev/null 2>&1; then
    chown root:gpio /etc/rpi-power-hat/hardware.conf 2>/dev/null || echo "Warning: Could not set ownership on hardware.conf"
    chmod 664 /etc/rpi-power-hat/hardware.conf 2>/dev/null || echo "Warning: Could not set permissions on hardware.conf"
fi

if [ -f /etc/rpi-power-hat/ports.conf ] && getent group gpio > /dev/null 2>&1; then
    chown root:gpio /etc/rpi-power-hat/ports.conf 2>/dev/null || echo "Warning: Could not set ownership on ports.conf"
    chmod 664 /etc/rpi-power-hat/ports.conf 2>/dev/null || echo "Warning: Could not set permissions on ports.conf"
fi

# Enable I2C if not already enabled (on Raspberry Pi)
if [ -f /boot/config.txt ]; then
    if ! grep -q "^dtparam=i2c_arm=on" /boot/config.txt; then
        echo "Enabling I2C interface..."
        echo "dtparam=i2c_arm=on" >> /boot/config.txt
        echo "Note: I2C enabled. A reboot may be required for changes to take effect."
    fi
fi

# Add current user to gpio group if running as non-root during install
if [ -n "$SUDO_USER" ]; then
    echo "Adding user $SUDO_USER to gpio and i2c groups..."
    usermod -a -G gpio "$SUDO_USER" 2>/dev/null || true
    usermod -a -G i2c "$SUDO_USER" 2>/dev/null || true
fi

# Ensure user's SSH config includes per-tool config.d snippets and legacy pi_config
if [ -n "$SUDO_USER" ]; then
    USER_HOME=$(eval echo "~$SUDO_USER")
    if [ -d "$USER_HOME" ]; then
        SSH_DIR="$USER_HOME/.ssh"
        mkdir -p "$SSH_DIR/config.d"
        # Create legacy pi_config as a child config if not present
        [ -f "$SSH_DIR/pi_config" ] || touch "$SSH_DIR/pi_config"
        # Ensure main config exists
        [ -f "$SSH_DIR/config" ] || touch "$SSH_DIR/config"
        # Prepend Include directive if missing
        if ! grep -qE '^[Ii]nclude[[:space:]]+~/.ssh/config.d/\*' "$SSH_DIR/config" 2>/dev/null; then
            TMP_FILE=$(mktemp)
            {
                echo "Include ~/.ssh/config.d/*"
                echo "Include ~/.ssh/pi_config"
                cat "$SSH_DIR/config"
            } > "$TMP_FILE"
            mv "$TMP_FILE" "$SSH_DIR/config"
        fi
        # Permissions
        chown -R "$SUDO_USER":"$SUDO_USER" "$SSH_DIR" 2>/dev/null || true
        chmod 700 "$SSH_DIR" 2>/dev/null || true
        chmod 700 "$SSH_DIR/config.d" 2>/dev/null || true
        chmod 600 "$SSH_DIR/config" 2>/dev/null || true
        chmod 600 "$SSH_DIR/pi_config" 2>/dev/null || true

        # Ensure pi_config includes our rpi-power-hat snippets directory
        if ! grep -qE '^[Ii]nclude[[:space:]]+~/.ssh/rpi-power-hat\.d/\*' "$SSH_DIR/pi_config" 2>/dev/null; then
            TMP_FILE2=$(mktemp)
            {
                echo "Include ~/.ssh/rpi-power-hat.d/*"
                cat "$SSH_DIR/pi_config"
            } > "$TMP_FILE2"
            mv "$TMP_FILE2" "$SSH_DIR/pi_config"
            chmod 600 "$SSH_DIR/pi_config" 2>/dev/null || true
        fi
    fi
fi

# If this looks like a git clone installation (source build), copy images
# This only works when installing from a built package in the source directory
if [ -n "$PWD" ] && [ -d "$PWD/init/images" ] && [ -d "$PWD/.git" ]; then
    echo "Detected source installation, copying OS images..."
    cp "$PWD/init/images"/* /var/lib/rpi-power-hat/images/ 2>/dev/null || echo "Warning: Could not copy images from $PWD/init/images/"
fi

# Verify installation (non-fatal - don't test hardware during package install)
echo "Verifying rpi-power-hat installation..."
if [ -x /usr/bin/rpi-power-hat ]; then
    echo "rpi-power-hat installation verified successfully."
else
    echo "Warning: rpi-power-hat executable not found at /usr/bin/rpi-power-hat"
fi

exit 0

