#!/bin/bash
#
#Copyright 2012 - 2017 CurlyMo & mkreisl <development@xbian.org>
#
#This file is part of XBian - XBMC on the Raspberry Pi.
#
#XBian 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.
#
#XBian 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 XBian. If not, see <http://www.gnu.org/licenses/>

# Get the current license
#  $1 [Container] License
# Returns
#  $LICENSE [String]
function getCurrentLicenseMPG2Fn() {
	LICENSE=$(sed -ne 's/\(^decode_MPG2=\)\(.*\)/\2/p' /boot/config.txt);
}

# Insert the current license
#  $1 [String] License
# Returns
#  * [Integer]
#  - 1: Success
#  - 0: Failed
function insertLicenseMPG2Fn() {
        L=$1; OIFS=$IFS; IFS=$','
	set -- $1
	[ $# -le 8 ] && rc=1 || rc=2
	for NEWLICENSE in $@; do
		if [ "${NEWLICENSE:0:2}" == "0x" ] && [[ "${NEWLICENSE:2:8}" =~ ^[0-9a-f]{1,8}$ ]] && [ ${#NEWLICENSE} -le 10 ] && [ ${#NEWLICENSE} -ge 9 ]; then
			:
		else
			rc=2
		fi
	done

	[ $rc == 1 ] && updateConfigVarFn decode_MPG2 "$L"

	IFS=$OIFS
	return $rc
}


# Update the current license
#  $1 [String] Current License
#  $2 [String] Old License
# Returns
#  * [Integer]
#  - 1: Success
#  - 0: Failed
function updateLicenseMPG2Fn() {
	insertLicenseMPG2Fn $1
}

# Delete the current license
#  $1 [String] Current License
# Returns
#  * [Integer]
#  - 1: Success
#  - 0: Failed
function deleteLicenseMPG2Fn() {
	grep -q ^"decode_MPG2=.*$1" /boot/config.txt && updateConfigVarFn decode_MPG2 0x00000000
	if [ $(grep -c $1 /boot/config.txt) -eq 0 ]; then
		return 1;
	else
		return 0;
	fi
}
