#!/bin/bash

# Author: Snow Yang
# Mail: yangsw@mxchip.com

help() {
    echo "Usage: pack.py [-h] -c CHIP [-o OPTION] -b BINARY -C CONF [-O OUTPUT]"
    echo ""
    echo "Options:"
    echo ""
    echo "  -h                    Print usage"
    echo "  -c string             Package tool name. (rtl87x2|bl602|mx1510)"
    echo "  -o string             Package tool Options"
    echo "                        For rtl87x2, parameters: select chip module (rtl8752/rtl8762)"
    echo "                        For bl602, parameters: select module (emc3025)"
    echo "  -b string             Input executable binary file generated by project"  
    echo "  -C string             Input configuration file"
    echo "  -O string             Output directory"                        

    exit -1
}

realpath() {
    [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}

check_docker() {
    docker -v $1>/dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "[Warning] Docker is required to generate OTA file on macOS."
        exit 0
    fi
}

while getopts 'c:o:b:C:O:h' OPT; do
    case $OPT in
    c) chip="$OPTARG" ;;
    o) option="$OPTARG" ;;
    b) binary="$OPTARG" ;;
    C) conf="$OPTARG" ;;
    O) output="$OPTARG" ;;
    ?) help ;;
    h) help ;;
    esac
done

# echo $chip
# echo $option
# echo $binary $(basename $binary) $(realpath $(dirname $binary))
# echo $conf $(basename $conf) $(realpath $(dirname $conf))
# echo $output $(realpath $output)

check_docker

if [ "$option" = "" ]
then
    option="."
fi

if [ "$output" = "" ]
then
    output="."
fi

if [ "$chip" = "" ] || [ "$binary" = "" ];then
    echo "Error: Missing arguments!"
    help
    exit -1
else
    if [ "$conf" = "" ];then
        docker run --rm -ti \
            -v $(realpath $(dirname $binary)):/input \
            -v $(realpath $output):/output \
            mxchip/hyperpacker python3 pack/pack.py -c $chip -o $option -b /input/$(basename $binary) \-O /output
    else
        docker run --rm -ti \
            -v $(realpath $(dirname $binary)):/input \
            -v $(realpath $output):/output \
            -v $(realpath $(dirname $conf)):/conf \
            mxchip/hyperpacker python3 pack/pack.py -c $chip -o $option -b /input/$(basename $binary) -C /conf/$(basename $conf) \-O /output
    fi
fi
