#!/bin/sh -x
##
## @package   tftp-update-manager
## @file      tftp-update-database-extractor.sh
## @brief     Script file for extracting database file from the given file.
##
## @author    Karthick Rajkumar
## @copyright Copyright 2022 Hanover Displays Limited.
## @license   This program is the confidential and proprietary product of
##            Hanover Displays Limited. Any unauthorised use, reproduction or
##            transfer of this program is strictly prohibited. (Subject to
##            limited distribution and restricted disclosure only.) All
##            rights reserved.
##

# command-line options verification.
if [ $# -ne 2 ]; then
    SCRIPT=$(basename $0)
    echo "Usage: ${SCRIPT} file-path destination-directory"
    exit 22
fi

SRC_FILE=${1:-""}
DST_FOLDER=${2:-""}

# source file validation
[ -f "${SRC_FILE}" ] || { echo "${SRC_FILE} is not a regular file."; exit 65; }

# creating destination folder if not exists
mkdir -p ${DST_FOLDER}

# clearing any existing files
rm -rf ${DST_FOLDER}/*

if expr "${SRC_FILE}" : ".*\.[Zz][Ii][Pp]\$"; then
    # zip file 
    unzip -o ${SRC_FILE} -d ${DST_FOLDER}
    EXIT_CODE=$?
    if [ ${EXIT_CODE} -ne 0 ]; then
        exit ${EXIT_CODE}
    fi
    ls -v ${DST_FOLDER} | wc -l
    DB_FILE=$(ls -v ${DST_FOLDER} | tail -n 1)
    mv ${DST_FOLDER}/${DB_FILE} ${DST_FOLDER}/ERIC.BIN
    rm -rf ${SRC_FILE}

elif expr "${SRC_FILE}" : ".*\.[Gg][Zz]\$"; then
    # gzip file
    mv "${SRC_FILE}" ${DST_FOLDER}/ERIC.BIN.gz
    gunzip -d ${DST_FOLDER}/ERIC.BIN.gz

elif expr "${SRC_FILE}" : ".*\.[Bb][Ii][Nn]\$"; then
    # bin file 
    mv ${SRC_FILE} ${DST_FOLDER}/ERIC.BIN
else
    # other file formats 
    mv ${SRC_FILE} ${DST_FOLDER}/ERIC.BIN
fi

exit $?
