#!/bin/sh

SOURCE_PATH=/app/config
c_option=""
d_option=""
path=""
deal_with_c=""
deal_with_d=""

usage() {
        echo "Usage:"
        echo "script -c [which path you want to save to]"
        echo "script -d [which path contains the compressed file]"
        exit 1
}

if [ $# -lt 1 ]; then
        usage
fi

while getopts ":c:d:" opt; do
        case ${opt} in
                c) 
                        c_option=$OPTARG 
                        deal_with_c="true"
                        ;;
                d) 
                        d_option=$OPTARG 
                        deal_with_d="true"
                        ;;
                \?)
                        echo "Invalid option: $OPTARG" 1>&2
                        usage
                        ;;
                :)
                        echo "Option -$OPTARG requires an argument." 1>&2
                        usage
                        ;;
        esac
done

path=$OPTARG

if [ "$deal_with_c" ]; then
	#To check if the path exists, if not, create it
        if [ -d $path ]; then
                echo "directory ${path} exists"
        else
                echo "Create directory ${pathi}"
                mkdir -p $path
        fi

        ARCHIVE_PATH=${path}/configuration_files.tar
	
	#prepare the command of tar, exclude some files
        tar --exclude='fac.ini' --exclude='uplink_channels.json' --exclude='rathole.toml' --exclude='proto_trigger_cfg.json' --exclude='frpc.ini' --exclude='ILITEK-tp-1280x800.conf' --exclude='lnxall_applist.json' --exclude="today_start_energy.json" -cvf ${ARCHIVE_PATH} -C ${SOURCE_PATH} .

        if [ -f "$ARCHIVE_PATH" ]; then
                echo "compression successful"
        else
                echo "compression failed"
        fi

        exit 0
fi

if [ "deal_with_d" ]; then
        ARCHIVE_PATH=${path}

	#To check if the compressed file exists.
        if [ ! -f ${ARCHIVE_PATH} ]; then
                echo "No compressed file found"
                exit 1
        fi

	#To check if source path exists, if not, create it
        if [ ! -d ${SOURCE_PATH} ]; then
                mkdir -p ${SOURCE_PATH}
        fi

	#decompress the file to source_path, it is always named /app/config
        tar -xvf ${ARCHIVE_PATH} -C ${SOURCE_PATH}/

	#set encode to UTF8
	export LC_ALL=zh_CN.utf8
        sed -i 's/"station_name"[[:space:]]*:[[:space:]]*".*"/"station_name": "默认站点名称"/g' /app/config/system_cfg.json

	#finally, delete the compressed file
        rm ${ARCHIVE_PATH}

        exit 0
fi
