#!/bin/sh

# Copyright (C) 2020  Braiins Systems s.r.o.
#
# This file is part of Braiins Open-Source Initiative (BOSI).
#
# BOSI is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# Please, keep in mind that we may also license BOSI or any part thereof
# under a proprietary license. For more information on the terms and conditions
# of such proprietary license or if you have any other questions, please
# contact us at opensource@braiins.com.

STAGE3_SCRIPT="stage3.sh"
BUILTIN_STAGE3_DIR="builtin"
USER_STAGE3_DIR="usr"

STAGE3_REFID="bos_refid"
STAGE3_REFERRAL="referral"
STAGE3_BOS_MGMT_ID="bos_mgmt_id"

BOS_REFERRAL_URL="https://referral.braiins-os.com"
BOS_REFERRAL_FEEDS_NAME="bos_referral"
BOS_CUSTOM_FEEDS_CFG="/etc/opkg/custombosfeeds.conf"

BOS_MGMT_ID_PATH="/etc/$STAGE3_BOS_MGMT_ID"

set -e

function run() {
    local root="$1"

	[ -f "$root/$STAGE3_SCRIPT" ] && (
		cd "$root"
		/bin/sh "$STAGE3_SCRIPT"
	)

	return 0
}

[ -f "$STAGE3_REFID" ] && {
	bos_refid=$(cat "$STAGE3_REFID")
	echo "Setting referral program server for id: $bos_refid"
	echo "src/gz $BOS_REFERRAL_FEEDS_NAME $BOS_REFERRAL_URL/$bos_refid" >> \
		"$BOS_CUSTOM_FEEDS_CFG"
}

[ -d "$STAGE3_REFERRAL" ] && {
	echo "Enabling referral program..."
	for ipk in "$STAGE3_REFERRAL/"*.ipk; do
		opkg install "$ipk"
	done
}

[ -f "$STAGE3_BOS_MGMT_ID" ] && {
	echo "Setting BOS management id: $(cat "$STAGE3_BOS_MGMT_ID")"
	cp "$STAGE3_BOS_MGMT_ID" "$BOS_MGMT_ID_PATH"
}

# test for built-in stage3 script and run it is separate shell
run "$BUILTIN_STAGE3_DIR"
# test for user defined stage3 script and run it is separate shell
run "$USER_STAGE3_DIR"

exit 0
