#!/bin/bash

set -e

MAX_WIDTH=1920
MAX_HEIGHT=1080
REQUIRED_DEPTH=24
MAX_COLOURS=224
DESTINATION_FILENAME=logo.tga
CMDLINE_FILENAME=/boot/firmware/cmdline.txt
CURRENT_DIR=$(pwd)
DO_IMAGE_CHECKS=1
DO_CMDLINE_UPDATE=1

# Parse command line arguments
usage() {
    echo "Usage: $0 <splash-image> [options]"
    echo "Use this tool to set up fullscreen splash screen on Raspberry Pi OS"
    echo "The splash image must be a ${REQUIRED_DEPTH}-bit TGA file, smaller than ${MAX_WIDTH}x${MAX_HEIGHT}px"
    echo "The image must also have less than ${MAX_COLOURS} colours"
    echo "This tool will alter cmdline.txt and initramfs to enable the splash screen"
    echo "Options:"
    echo "  -h, --help              Show this help message"
    echo "  --skip-image-checks   Ignore image checks and continue anyway"
    echo "  --no-cmdline          Do not alter cmdline.txt"
    exit 1
}

if [ $# -eq 0 ]; then
    echo "Error: No splash image provided"
    usage
fi

for arg in "$@"; do
    case $arg in
        --skip-image-checks)
            DO_IMAGE_CHECKS=0
            ;;
        --no-cmdline)
            DO_CMDLINE_UPDATE=0
            ;;
        -h|--help)
            usage
            ;;
    esac
done

IMAGE_PATH="$1"

if ! IMAGE_PATH=$(realpath -e "$IMAGE_PATH" 2>/dev/null); then
    echo "Error: Splash image file not found"
    exit 1
fi

IMAGE_INFO=$(file "$IMAGE_PATH")

# Check if the image is a valid TGA file
if ! echo "$IMAGE_INFO" | grep -q "Targa image"; then
    echo "Error: Splash image is not a valid TGA file"
    exit 1
fi

if [ $DO_IMAGE_CHECKS -eq 1 ]; then
    echo "Checking image is valid"
    # Make sure image dimensions not too large
    regex="([0-9]+) x ([0-9]+) x ([0-9]+)"

    # Perform the regex match
    if [[ $IMAGE_INFO =~ $regex ]]; then
        # Assign the captured groups to variables
        width=${BASH_REMATCH[1]}
        height=${BASH_REMATCH[2]}
        depth=${BASH_REMATCH[3]}
        if [ $depth -ne $REQUIRED_DEPTH ]; then
        echo "Error: Splash image must be $REQUIRED_DEPTH-bit, provided image is $depth bit"
        exit 1
        fi
        if [ $width -gt $MAX_WIDTH ] || [ $height -gt $MAX_HEIGHT ]; then
            echo "Splash image must be less than $MAX_WIDTH x $MAX_HEIGHT px"
            echo "Provided image is $width x $height"
            exit 1
        fi
    else
        echo "Could not determine image properties"
        echo "Warning: Continuing anyway, please check image is correct format:"
        echo "Image format must be TGA, ${REQUIRED_DEPTH}-bit, dimensions < ${MAX_WIDTH}x${MAX_HEIGHT}px"
    fi
else
    echo "Warning: skipping image checks"
fi

# Everything beyond here needs root access
if [  $(id -u) -ne 0 ]; then
    echo "Script must be run as root. Try 'sudo $0'"
    exit 1
fi

# Add correct hook to /etc/initramfs-tools/hooks/
echo "Copying image to /lib/firmware/${DESTINATION_FILENAME}"
cp "$IMAGE_PATH" /lib/firmware/${DESTINATION_FILENAME}

echo "Adding hook to /etc/initramfs-tools/hooks/"
cp /usr/share/rpi-splash-screen-support/default-hook.sh /etc/initramfs-tools/hooks/splash-screen-hook.sh
sed -i "s|splash-image-path|${DESTINATION_FILENAME}|" /etc/initramfs-tools/hooks/splash-screen-hook.sh

echo "Updating initramfs"
update-initramfs -k all -u

NEW_PARAMS=("fullscreen_logo=1" "fullscreen_logo_name=${DESTINATION_FILENAME}" "vt.global_cursor_default=0")

if [ $DO_CMDLINE_UPDATE -eq 1 ]; then
    # Update cmdline.txt to enable splash screen
    # Remove entries that will conflict with fullscreen splash
    echo "Altering $CMDLINE_FILENAME to enable splash screen"

    sed -i "s/\bconsole=tty1\b//" $CMDLINE_FILENAME
    sed -i "s/\bplymouth.ignore-serial-consoles\b//" $CMDLINE_FILENAME
    sed -i "s/\bquiet\b//" $CMDLINE_FILENAME

    CMDLINE="$(tr -d '\n' < $CMDLINE_FILENAME)"

    # Remove any existing versions of our params (with any value)
    for p in "${NEW_PARAMS[@]}"; do
        key=${p%%=*}
        CMDLINE="$(echo "$CMDLINE" | sed -E "s/\b${key}=[^ ]*//g")"
    done

    CMDLINE="$(echo "$CMDLINE" | tr -s ' ')"
    CMDLINE="$(echo "$CMDLINE" | sed -E 's/^ +| +$//g')"

    # Append the correct parameters
    for p in "${NEW_PARAMS[@]}"; do
        CMDLINE="$CMDLINE $p"
    done

    # Ensure it's still a single line
    echo "$CMDLINE" | tr -d '\n' > $CMDLINE_FILENAME
    echo "Updated $CMDLINE_FILENAME"
else
    echo "Not updating $CMDLINE_FILENAME"
    echo "To enable the splash screen, you must manually add the following entries to $CMDLINE_FILENAME:"
    for p in "${NEW_PARAMS[@]}"; do
        echo "$p"
    done
fi
