#!/bin/bash
#------------------------------------------------------------------------
#
#       $Id: lts3_gen_cardheader.sh 541 2015-09-04 08:18:34Z yoshida.naoto $
#       
#                       COPYRIGHT 2015 BY
#                     MegaChips Corporation
#
#------------------------------------------------------------------------
#       PROJECT: LTS3
#      CATEGORY: --Shell--
#         LEVEL:
#   ENVIRONMENT: sh
#       $Author: yoshida.naoto $
#         $Date: 2015-09-04 17:18:34 +0900 (Fri, 04 Sep 2015) $
#     $Revision: 541 $
#       COMMENT: Lotus3 CardHeader generation shell script
#------------------------------------------------------------------------


#######################
# Arg                 #
#######################

#Number of Publication argument
PUB_ARG_NUM=19

#Publication argument
OUTPUT_FILE=$1
PRIVATEKEY_FILE=$2
SK_FILE=$3
IV_FILE=$4
ROM_START_PA=$5
BACKUP_START_PA=$6
TITLEID_NUM=$7
SELSEC_NUM=$8
SELT1KEY_NUM=$9
SELKEY_NUM=${10}
LIMAREA_NUM=${11}
FWVERSION_NUM=${12}
ACCCTRL1_NUM=${13}
WAIT1TIMEREAD_NUM=${14}
WAIT1TIMEWRITE_NUM=${15}
WAIT2TIMEREAD_NUM=${16}
WAIT2TIMEWRITE_NUM=${17}
FWMODE_NUM=${18}
CUPVERSION_NUM=${19}

#Input number of argument
ARG_NUM=$#


#######################
# Parameter           #
#######################

#Data byte size(ARG)
SK_SIZE=16
IV_SIZE=16
ROM_START_PA_SIZE=4
BACKUP_START_PA_SIZE=4
TITLEID_SIZE=8
SELSEC_SIZE=4
SELT1KEY_SIZE=4
SELKEY_SIZE=4
LIMAREA_SIZE=4
FWVERSION_SIZE=8
ACCCTRL1_SIZE=4
WAIT1TIMEREAD_SIZE=4
WAIT1TIMEWRITE_SIZE=4
WAIT2TIMEREAD_SIZE=4
WAIT2TIMEWRITE_SIZE=4
FWMODE_SIZE=4
CUPVERSION_SIZE=4

#Extension flag
PEM_FLAG=0
DER_FLAG=1

#Binary Data
RESERVED="\x00"
H="\x48"
E="\x45"
A="\x41"
D="\x44"


#######################
# Dir Path            #
#######################

TMP_PATH="./__tmp"


#######################
# File Name           #
#######################

#Executable file name
OPENSSL="openssl"

#Temp File Name
tmpENCTARGET_FILE=$TMP_PATH/"__tmpEncTarget.bin"
tmpENCCBC_FILE=$TMP_PATH/"__tmpEncCbc.bin"
tmpSIGNTARGET_FILE=$TMP_PATH/"__tmpSignTarget.bin"
tmpCARDHEADER_0x100_0x18F_FILE=$TMP_PATH/"__tmpCardHeader(0x100-0x18F).bin"
tmpPRIVATEKEY_DER=$TMP_PATH/"__tmpPrivatekey.der"
tmpSIGN_FILE=$TMP_PATH/"__tmpSign.bin"

#Output(Body) File Name
case "$OUTPUT_FILE" in
 *./*)
   current="./"
   ;;
 *)
   current=""
   ;;
esac

BODY_FILE=`echo $OUTPUT_FILE | sed -e "s/\.\///"`
filename_woextension=${BODY_FILE%.*}

case "$BODY_FILE" in
*.*)
  extension="."${BODY_FILE##*.}
  ;;
*)
  extension=""
  ;;
esac
body_filename=$current$filename_woextension"_body"$extension

#######################
# Success Messeage    #
#######################

NO1_SUCCESS="==============================================\n Output generation file\n \"$OUTPUT_FILE & $body_filename\"\n Generating CardHeader was successful!!\n==============================================\n"


#######################
# Error Messeage      #
#######################

NO1_ERR="ERROR 1: File format of CA Private Key(arg2) is not PEM or DER"
NO2_ERR="ERROR 2: File format of SK (arg3) is not BIN."
NO3_ERR="ERROR 3: Size of SK (arg3) is not 16Byte."
NO4_ERR="ERROR 4: File format of IV (arg4) is not BIN."
NO5_ERR="ERROR 3: Size of IV (arg4) is not 16Byte."
NO6_ERR="ERROR 6: Size of ROM Area Start Page Address (arg5) is not 4Byte."
NO7_ERR="ERROR 7: Size of Backup Area Start Page Address (arg6) is not 4Byte."
NO8_ERR="ERROR 8: Size of Title ID (arg7) is not 8Byte."
NO9_ERR="ERROR 9: Size of SEL_SEC (arg8) is not 4Byte."
NO10_ERR="ERROR 10: Size of SEL_T1_KEY (arg9) is not 4Byte."
NO11_ERR="ERROR 11: Size of SEL_KEY (arg10) is not 4Byte."
NO12_ERR="ERROR 12: Size of Lim_Area (arg11) is not 4Byte."
NO13_ERR="ERROR 13: Size of FwVersion (arg12) is not 8Byte."
NO14_ERR="ERROR 14: Size of ACC_CTRL1 (arg13) is not 4Byte."
NO15_ERR="ERROR 15: Size of WAIT1_TIME_READ (arg14) is not 4Byte."
NO16_ERR="ERROR 16: Size of WAIT1_TIME_WRITE (arg15) is not 4Byte."
NO17_ERR="ERROR 17: Size of WAIT2_TIME_READ (arg16) is not 4Byte."
NO18_ERR="ERROR 18: Size of WAIT2_TIME_WRITE (arg17) is not 4Byte."
NO19_ERR="ERROR 19: Size of FwMode (arg18) is not 4Byte."
NO20_ERR="ERROR 20: Size of CUP Version (arg19) is not 4Byte."
NO21_ERR="ERROR 21: No such file " #Add file name
NO22_ERR="ERROR 22: Don't use '0x'(arg" #Add number of arg & ).
NO23_ERR="ERROR 23: Don't use other hex value(arg" #Add number of argi & ).
NO24_ERR="ERROR 24: Number of argument is too many."
NO25_ERR="ERROR 25: Number of argument is few."
NO26_ERR="ERROR 26: Output file's name (arg1) is directory name."


#######################
# Process             #
#######################

#-------------------------------------
#Arg    : $1: Check target file
#         $2: Lowercase extension
#         $3: Error messeage 
#Output : -
#COMMENT: File exist check
#-------------------------------------
function fileexist_check() {

  #File check
  if [ ! -e "$1" ]; then
    echo $NO21_ERR $1
    exit
  fi

  #Extension check
  low=$2                               #Lowercase extension
  up=`echo $low | tr '[a-z]' '[A-Z]'`  #Uppercase extension
  case "$1" in
   *.$low)
    ;;
   *.$up)
    ;;
   *)
    echo $3
    exit
  esac
}


#-------------------------------------
#Arg    : $1: Check target file
#         $2: Expected file size
#         $3: Error messeage 
#Output : -
#COMMENT: File size check
#-------------------------------------
function filesize_check() {
    
  #File size check
  size=`cat $1 | wc -c` 
  exp_size=$2

  if [ "$size" -ne "$exp_size" ]; then
    echo $3
    exit
  fi
}


#-------------------------------------
#Arg    : $1: Check text
#         $2: Arg number
#         $3: Expected text size
#         $4: Error messeage 
#Output : -
#COMMENT: Text file check
#-------------------------------------
function text_check() {

  #'0x' check
  case "$1" in
  0x*)
    ;;
  *)
    echo $NO22_ERR$2")."
    exit
  esac

  #Size check
  exp_size=`expr $3 \* 2 ` #1Byte is 2 strings
  tmp=`echo $1 | sed -e "s/\0x//"`
  if [ ${#tmp} -ne "$exp_size" ]; then
    echo $4
    exit
  fi
  
  #String check
  tmp2=`echo $tmp | sed -e "s/[0-9,a-f,A-F]//g"`  
  if [ ${#tmp2} -ne 0 ]; then
    echo $NO23_ERR$2")."
    exit
  fi
}


#-------------------------------------
#Arg    : -
#Output : -
#COMMENT: Argument Check
#-------------------------------------
function checkArg() {

  #Number of Arg(many? or few?)
  if [ "$ARG_NUM" -gt "$PUB_ARG_NUM" ]; then
    echo $NO24_ERR
    exit
  fi
  if [ "$ARG_NUM" -lt "$PUB_ARG_NUM" ]; then
    echo $NO25_ERR
    exit
  fi

  #Arg1 Check
  if [ -d "$OUTPUT_FILE" ]; then
    echo $NO26_ERR 
    exit
  fi
  
  #Arg2 Check
  if [ ! -e "$PRIVATEKEY_FILE" ]; then
    echo $NO21_ERR $PRIVATEKEY_FILE
    exit
  fi

  case "$PRIVATEKEY_FILE" in
   *.pem)
    extension=$PEM_FLAG 
    ;;
   *.PEM)
    extension=$PEM_FLAG 
    ;;
   *.der)
    extension=$DER_FLAG 
    ;;
   *.DER)
    extension=$DER_FLAG 
    ;;
   *)
    echo $NO1_ERR
    exit
  esac

  #Arg3 Check
  fileexist_check $SK_FILE "bin" "$NO2_ERR"
  filesize_check $SK_FILE $SK_SIZE "$NO3_ERR"

  #Arg4 Check
  fileexist_check $IV_FILE "bin" "$NO4_ERR"
  filesize_check $IV_FILE $IV_SIZE "$NO5_ERR"

  #Arg5 Check
  text_check $ROM_START_PA "5" $ROM_START_PA_SIZE "$NO6_ERR"
  
  #Arg6 Check
  text_check $BACKUP_START_PA "6" $BACKUP_START_PA_SIZE "$NO7_ERR"

  #Arg7 Check
  text_check $TITLEID_NUM "7" $TITLEID_SIZE "$NO8_ERR"

  #Arg8 Check
  text_check $SELSEC_NUM "8" $SELSEC_SIZE "$NO9_ERR"
  
  #Arg9 Check
  text_check $SELT1KEY_NUM "9" $SELT1KEY_SIZE "$NO10_ERR"

  #Arg10 Check
  text_check $SELKEY_NUM "10" $SELKEY_SIZE "$NO11_ERR"

  #Arg11 Check
  text_check $LIMAREA_NUM "11" $LIMAREA_SIZE "$NO12_ERR"

  #Arg12 Check
  text_check $FWVERSION_NUM "12" $FWVERSION_SIZE "$NO13_ERR"

  #Arg13 Check
  text_check $ACCCTRL1_NUM "13" $ACCCTRL1_SIZE "$NO14_ERR"

  #Arg14 Check
  text_check $WAIT1TIMEREAD_NUM "14" $WAIT1TIMEREAD_SIZE "$NO15_ERR"

  #Arg15 Check
  text_check $WAIT1TIMEWRITE_NUM "15" $WAIT1TIMEWRITE_SIZE "$NO16_ERR"

  #Arg16 Check
  text_check $WAIT2TIMEREAD_NUM "16" $WAIT2TIMEREAD_SIZE "$NO17_ERR"

  #Arg17 Check
  text_check $WAIT2TIMEWRITE_NUM "17" $WAIT2TIMEWRITE_SIZE "$NO18_ERR"
  
  #Arg18 Check
  text_check $FWMODE_NUM "18" $FWMODE_SIZE "$NO19_ERR"
  
  #Arg19 Check
  text_check $CUPVERSION_NUM "19" $CUPVERSION_SIZE "$NO20_ERR"
}


#-------------------------------------
#Arg    : $1: Binary file
#Output : Binary data
#COMMENT: Read binary file
#-------------------------------------
function readbin() {
  totxt=`od -t xC $1 | head -n 1 | sed -e "s/^0* \(.*\)/\1/"`
  readbin=""
  for item in $totxt 
  do
    readbin=$readbin"\x$item"
  done
}


#-------------------------------------
#Arg    : $1: Text file
#Output : Binary data
#COMMENT: Generation binary file
#-------------------------------------
function tex2binle() {
  tex2bin=""
  for (( i = ${#1} ; i > 0 ; i-=2 )) 
  do
    f=`expr $i - 1`
    num=`echo $1 | cut -c $f-$i`
    tex2bin=$tex2bin"\x$num"
  done
}


#-------------------------------------
#Arg    : -
#Output : tmpENCTARGET_FILE
#COMMENT: Generation target file (AES128-CBC)
#-------------------------------------
function genEncTargetFile() {

  enc_target=""

  #FW Version
  FWVERSION_NUM=`echo $FWVERSION_NUM | sed -e "s/\0x//"`
  tex2binle $FWVERSION_NUM; enc_target=$enc_target$tex2bin
  
  #ACC_CTRL1
  ACCCTRL1_NUM=`echo $ACCCTRL1_NUM | sed -e "s/\0x//"`
  tex2binle $ACCCTRL1_NUM; enc_target=$enc_target$tex2bin
  
  #WAIT1_TIME_READ
  WAIT1TIMEREAD_NUM=`echo $WAIT1TIMEREAD_NUM | sed -e "s/\0x//"`
  tex2binle $WAIT1TIMEREAD_NUM; enc_target=$enc_target$tex2bin

  #WAIT2_TIME_READ
  WAIT2TIMEREAD_NUM=`echo $WAIT2TIMEREAD_NUM | sed -e "s/\0x//"`
  tex2binle $WAIT2TIMEREAD_NUM; enc_target=$enc_target$tex2bin
 
  #WAIT1_TIME_WRITE
  WAIT1TIMEWRITE_NUM=`echo $WAIT1TIMEWRITE_NUM | sed -e "s/\0x//"`
  tex2binle $WAIT1TIMEWRITE_NUM; enc_target=$enc_target$tex2bin

  #WAIT2_TIME_WRITE
  WAIT2TIMEWRITE_NUM=`echo $WAIT2TIMEWRITE_NUM | sed -e "s/\0x//"`
  tex2binle $WAIT2TIMEWRITE_NUM; enc_target=$enc_target$tex2bin

  #FwMode
  FWMODE_NUM=`echo $FWMODE_NUM | sed -e "s/\0x//"`
  tex2binle $FWMODE_NUM; enc_target=$enc_target$tex2bin

  #CUP Version
  CUPVERSION_NUM=`echo $CUPVERSION_NUM | sed -e "s/\0x//"`
  tex2binle $CUPVERSION_NUM; enc_target=$enc_target$tex2bin

  #Reserved(76Byte)
  for i in `seq 0 75`
  do
   enc_target=$enc_target$RESERVED
  done
   
  #Create encrypt target file
  echo -en $enc_target > $tmpENCTARGET_FILE
}


#-------------------------------------
#Arg    : -
#Output : $tmpENCCBC_FILE
#COMMENT: Encrypt (AES128-CBC)
#-------------------------------------
function encryptCBC() {
  sk=`od -A n -tx1 $SK_FILE | sed -e "s/\s/""/g"`
  iv=`od -A n -tx1 $IV_FILE | sed -e "s/\s/""/g"`
  $OPENSSL aes-128-cbc -e -nopad -K $sk -iv $iv  -in $tmpENCTARGET_FILE -out $tmpENCCBC_FILE
}


#-------------------------------------
#Arg    : -
#Output : $tmpSIGNTARGET_FILE
#COMMENT: Generation target file (Sign)
#-------------------------------------
function genSignTargetFile() {

  sign_target=""
  
  #Fix value set
  sign_target=$sign_target$H
  sign_target=$sign_target$E
  sign_target=$sign_target$A
  sign_target=$sign_target$D

  #Rom Area Sttart Page Address
  ROM_START_PA=`echo $ROM_START_PA | sed -e "s/\0x//"`
  tex2binle $ROM_START_PA; sign_target=$sign_target$tex2bin
  
  #Backup Area Sttart Page Address
  BACKUP_START_PA=`echo $BACKUP_START_PA | sed -e "s/\0x//"`
  tex2binle $BACKUP_START_PA; sign_target=$sign_target$tex2bin
  
  #Reserved(4Byte)
  for i in `seq 0 3`
  do
   sign_target=$sign_target$RESERVED
  done
   
  #Titile ID
  TITLEID_NUM=`echo $TITLEID_NUM | sed -e "s/\0x//"`
  tex2binle $TITLEID_NUM; sign_target=$sign_target$tex2bin

  #Reserved(8Byte)
  for i in `seq 0 7`
  do
   sign_target=$sign_target$RESERVED
  done
  
  #IV
  iv=`od -A n -tx1 $IV_FILE | sed -e "s/\s/""/g"`
  tex2binle $iv; sign_target=$sign_target$tex2bin
 
  #Reserved(80Byte)
  for i in `seq 0 79`
  do
   sign_target=$sign_target$RESERVED
  done

  #SEL_SEC
  SELSEC_NUM=`echo $SELSEC_NUM | sed -e "s/\0x//"`
  tex2binle $SELSEC_NUM; sign_target=$sign_target$tex2bin

  #SEL_T1_KEY
  SELT1KEY_NUM=`echo $SELT1KEY_NUM | sed -e "s/\0x//"`
  tex2binle $SELT1KEY_NUM; sign_target=$sign_target$tex2bin

  #SEL_KEY
  SELKEY_NUM=`echo $SELKEY_NUM | sed -e "s/\0x//"`
  tex2binle $SELKEY_NUM; sign_target=$sign_target$tex2bin

  #LIM_AREA
  LIMAREA_NUM=`echo $LIMAREA_NUM | sed -e "s/\0x//"`
  tex2binle $LIMAREA_NUM; sign_target=$sign_target$tex2bin

  #Generation target file (Sign)
  echo -en $sign_target > $tmpCARDHEADER_0x100_0x18F_FILE
  cat $tmpCARDHEADER_0x100_0x18F_FILE $tmpENCCBC_FILE > $tmpSIGNTARGET_FILE
}


#-------------------------------------
#Arg    : -
#Output : $tmpSIGN_FILE
#COMMENT: Sign
#-------------------------------------
function sign() {

  #If extension of private key file is "PEM"
  if [ 0 -eq $extension ]; then
    #Change Pem -> DER 
    $OPENSSL rsa -inform PEM -outform DER -in $PRIVATEKEY_FILE -out $tmpPRIVATEKEY_DER
    $OPENSSL dgst -sha256 -sign $tmpPRIVATEKEY_DER -keyform der -out $tmpSIGN_FILE $tmpSIGNTARGET_FILE
  else #If extension of private key file is "DER"
    $OPENSSL dgst -sha256 -sign $PRIVATEKEY_FILE -keyform der -out $tmpSIGN_FILE $tmpSIGNTARGET_FILE
  fi
}

#-------------------------------------
#Arg    : -
#Output : $body_filename & $OUTPUT_FILE(arg1)
#COMMENT: Generation CardHeader & CardHeaderBody file
#-------------------------------------
function genCardHeaderFile() {

  cat $tmpCARDHEADER_0x100_0x18F_FILE $tmpENCTARGET_FILE > $body_filename
  cat $tmpSIGN_FILE $tmpSIGNTARGET_FILE > $OUTPUT_FILE
  printf "$NO1_SUCCESS"
}


#######################
# Main Sequence       #
#######################
mkdir -p $TMP_PATH

checkArg
genEncTargetFile
encryptCBC
genSignTargetFile
sign
genCardHeaderFile

#rm -Rf $TMP_PATH


