Skip to content

Instantly share code, notes, and snippets.

@phongnh
Forked from naoki-mizuno/flash-hhkb-yang
Created May 23, 2023 11:36
Show Gist options
  • Save phongnh/aee9388179870459693c6b43474bfe90 to your computer and use it in GitHub Desktop.
Save phongnh/aee9388179870459693c6b43474bfe90 to your computer and use it in GitHub Desktop.
#!/bin/bash
BIN_FILE="$1"
PAD_BIN_FILE="true"
BEFORE="$( ls -1 /dev/sd? )"
if [[ ! -f $BIN_FILE ]]; then
echo "Hmm... can't find firmware file at $BIN_FILE" 2>&1
exit 1
fi
# Pad file to make it exactly 26 KB
if [[ $PAD_BIN_FILE == "true" ]]; then
TARGET_SIZE=26624
ORIG_SIZE="$( du -b $BIN_FILE | awk '{ print $1 }' )"
echo "Original file size is $ORIG_SIZE bytes"
if [[ $TARGET_SIZE == $ORIG_SIZE ]]; then
echo "No need to pad"
else
# Create backup file just in case
cp $BIN_FILE $BIN_FILE.orig
dd if=/dev/null of=$BIN_FILE bs=1 count=1 seek=26624 2>/dev/null
# Note: Another way to do this
# truncate -s 26K $BIN_FILE
echo "Padded $BIN_FILE to 26624 bytes"
fi
fi
echo "You may be prompted for your password so this script can execute sudo"
sudo echo "OK! You can now plug in your keyboard in flash mode" || exit 0
while true; do
AFTER="$( ls -1 /dev/sd? )"
PLUGGED_IN="$( diff <( echo "$BEFORE" | sort ) <( echo "$AFTER" | sort ) | awk '/^> /{ print $2 }' )"
if [[ -n $PLUGGED_IN ]]; then
break
fi
sleep 0.5
done
echo "Detected new device at $PLUGGED_IN"
for t in {9..1}; do
echo -n -e "Flashing $PLUGGED_IN in $t\r"
sleep 1
done
if [[ ! -e $PLUGGED_IN ]]; then
echo "$PLUGGED_IN seemed to have disappeared. Did you pull it out?" 2>&1
exit 1
fi
echo -e "\nFlashing!"
sudo dd if="$BIN_FILE" of="$PLUGGED_IN" seek=4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment