#!/bin/bash

### Use PKG_DIR as working directory.
PKG_DIR="/tmp/_MyApplication_pkg"	# temp folder for package files
rm -rf $PKG_DIR
mkdir -p $PKG_DIR

### get spk packing functions
source /pkgscripts/include/pkg_util.sh
source /toolkit/pkgscripts-ng/include/pkg_util.sh

create_package_tgz() {
	local package_tgz_dir=/tmp/_package_tgz

	### clear destination directory
	rm -rf $package_tgz_dir && mkdir -p $package_tgz_dir

	### install needed file into PKG_DIR
	cp -av ui $package_tgz_dir
	cp -av etc $package_tgz_dir
	cp -av webapps/* $package_tgz_dir
	chown -R http:http $package_tgz_dir/webapps

	### create package.tgz $1: source_dir $2: dest_dir
	pkg_make_package $package_tgz_dir "${PKG_DIR}"
}

create_spk() {
	cp -av scripts $PKG_DIR/scripts
	cp -av conf $PKG_DIR
	cp -av ui $PKG_DIR
	cp -av build/* $PKG_DIR/ui/
	cp -av LICENSE $PKG_DIR
	cp -av ui/icons/MyIcon_72.png  $PKG_DIR/PACKAGE_ICON.PNG
	cp -av ui/icons/MyIcon_256.png $PKG_DIR/PACKAGE_ICON_256.PNG

	./INFO.sh > INFO
	cp INFO $PKG_DIR/INFO

	### Create the final spk.
	# pkg_make_spk <source path> <dest path> <spk file name>
	# Please put the result spk into /image/packages
	# spk name functions: pkg_get_spk_name pkg_get_spk_unified_name pkg_get_spk_family_name
	mkdir -p /image/packages
	pkg_make_spk ${PKG_DIR} "/image/packages" $(pkg_get_spk_family_name)
}

main() {
	create_package_tgz
	create_spk
}

main "$@"
