#!/bin/sh

# Some constants
# Controller pseudo-file
clovercon=/dev/input/by-path/platform-twi.1-event-joystick
# Password pattern - it's Konami Code :)
password="c202 c202 c302 c302 c002 c102 c002 c102 3101 3001 3b01"
# Max tries
max_tries=30

# Init scripts are executed with "start" argument when system boots and with "stop" argument during shutdown
# So we need to check that it's boot state, not shutdown
[ -z "$1" ] || [ "$1" == "start" ] || exit 0

# Drawing "ENTER PASSWORD" image
gunzip -c /etc/password.raw.gz > /dev/fb0

# Endless loop
while [ true ]; do
  # Wait while pseudo-file doesn't exists (controller is not connected or is not initialized yet)
  while [ ! -e $clovercon ]; do usleep 100; done
  # Reading buttons
  buttons=$(cat $clovercon | hexdump -v -e '1/1 "%02x"' -n 32)     
  buttons=${buttons:20:4}
  # Appending pressed button to "str" variable
  str="$str $buttons"
  # If "str" variable is longer than password string, cut it
  # So we get only last presses
  [ "${#str}" -gt "${#password}" ] && str="${str:$((${#str}-${#password})):${#password}}"

  # Is password correct?    
  if [ "$str" == "$password" ]; then
    # Display "OK" image
    gunzip -c /etc/password_ok.raw.gz > /dev/fb0
    # Exit and continue system loading
    exit 0
  fi

  # Password is not correct yet, decrease tries counter
  max_tries=$(($max_tries-1))
  # Is it zero?
  if [ "$max_tries" == "0" ]; then
    # Display "ACCESS DENIED" image
    gunzip -c /etc/password_fail.raw.gz > /dev/fb0
    # Wait for three seconds
    sleep 3
    # Shutdown system
    poweroff
  fi
done
