Skip to content

Instantly share code, notes, and snippets.

@TheGammaSqueeze
Created April 28, 2024 10:55
Show Gist options
  • Select an option

  • Save TheGammaSqueeze/9e0134417cf763e605ddc0c699c0763f to your computer and use it in GitHub Desktop.

Select an option

Save TheGammaSqueeze/9e0134417cf763e605ddc0c699c0763f to your computer and use it in GitHub Desktop.
Decodes and Encodes Allwinner env files
#!/bin/bash
# Path to the environment file
ENV_FILE="$1"
# Function to decode the environment file to text
decode_env() {
# Skip the special header (assuming header length + null byte), convert null bytes to newlines, then strip trailing null bytes (represented by empty lines)
tail -c +6 "$ENV_FILE" | tr '\0' '\n' | sed '/^$/d' # Remove empty lines which are the result of trailing null bytes
}
# Function to encode text back to the environment file format
encode_env() {
SOURCE_FILE="$2"
TARGET_SIZE="$3"
if [[ -z "$TARGET_SIZE" || ! "$TARGET_SIZE" =~ ^[0-9]+$ ]]; then
echo "Target size in bytes must be specified for encoding and must be a number."
exit 1
fi
# Create a new file to avoid overwriting during tests
NEW_ENV_FILE="${ENV_FILE}.new"
# Add the special header including the null byte at the end
echo -en '\xe1\xfa\x10\x62\0' > "$NEW_ENV_FILE"
# Convert newlines in the source file to null bytes and append to the new file in one go
tr '\n' '\0' < "$SOURCE_FILE" >> "$NEW_ENV_FILE"
# Calculate current size and pad if necessary
CURRENT_SIZE=$(stat -c "%s" "$NEW_ENV_FILE")
PADDING_SIZE=$(( TARGET_SIZE - CURRENT_SIZE ))
if [ "$PADDING_SIZE" -gt 0 ]; then
# Creating and appending zero block in memory
head -c "$PADDING_SIZE" /dev/zero >> "$NEW_ENV_FILE"
fi
}
# Argument checks and action determination
if [ "$#" -lt 2 ]; then
echo "Usage for decode: $0 <env_file> decode"
echo "Usage for encode: $0 <env_file> encode <source_file_for_encode> <target_size_for_encode>"
exit 1
fi
ACTION="$2"
case $ACTION in
decode)
decode_env
;;
encode)
if [ "$#" -ne 4 ]; then
echo "Usage for encode: $0 <env_file> encode <source_file_for_encode> <target_size_for_encode>"
exit 1
fi
encode_env "$ENV_FILE" "$3" "$4"
;;
*)
echo "Invalid action: $ACTION"
echo "Valid actions are 'decode' or 'encode'"
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment