#!/bin/bash

###########################################################################
#
# MODULE:       Scripts
# COPYRIGHT:    (C) 2009-2025 by CacheGuard Technologies Ltd (UK)
# COPYRIGHT:    (C) 2026-2026 by CacheGuard Technologies SAS (FR)
#
# This program 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 <http://www.gnu.org/licenses/>.
#
###########################################################################

source /lib/lsb/init-functions
source ${IFCONFIG}

if test -z "${VLAN_ID}" ; then
    log_failure_msg "VLAN_ID variable missing from ${IFCONFIG}, cannot continue."
    exit 1
fi

802-1q-up()
{
    test -n "${1}" || return 1
    test -n "${2}" || return 2
    local dev=${1}
    local vlan=${2}

    local dev_base=${dev/\.*}

    test ${dev} != ${dev_base} || return 3
    test ${vlan} == ${dev/*\.} || return 4
    
    ip link set dev ${dev_base} up
    ip link add link ${dev_base} name ${dev_base}.${vlan} type vlan id ${vlan}
}

802-1q-down()
{
    test -n "${1}" || return 1
    test -n "${2}" || return 2
    local dev=${1}
    local vlan=${2}

    local dev_base=${dev/\.*}

    test ${dev} != ${dev_base} || return 3
    test ${vlan} == ${dev/*\.} || return 4

    ip link del dev ${dev_base}.${vlan}
}

case "${2}" in
    up)
	log_info_msg "Adding '${VLAN_ID}' 802.1q tagged interface..."
	802-1q-up ${1} "${VLAN_ID}"
	evaluate_retval
	;;
    down)
	log_info_msg "Removing '${VLAN_ID}' 802.1q tagged interface..."
	802-1q-down ${1} "${VLAN_ID}"
	evaluate_retval
	;;
    *)
	echo "Usage: ${0} [interface] {up|down}"
	exit 1
	;;
esac
