#!/bin/bash

SELF_DIR="$(dirname $(readlink -e ${0}))"
BASE_DIR="$(dirname $(dirname ${SELF_DIR}))"
SCRIPTCOMMON="${BASE_DIR}/scripts_common.sh"

. ${SCRIPTCOMMON}

IPTABLES="sudo iptables"
XPATH="${BASE_DIR}/datastore/xpath.rb --stdin --base64"

RULES_FILE="/run/one/one_graphics_rules"

function one_get_port()
{
    ${XPATH} ${1} '/VM/TEMPLATE/GRAPHICS/PORT'
}

function open_port()
{
    declare -a authorized_ip
    declare -a authorized_netmask

    vm_port=$(one_get_port ${1})
    [[ -z "${vm_port}" ]] && return 2
    authorized_ip=( $(CreoleGet ip_ssh_eth0) )
    [[ -z "${authorized_ip}" ]] && return 2
    authorized_netmask=( $(CreoleGet netmask_ssh_eth0) )
    [[ -z "${authorized_netmask}" ]] && return 2

    for ((i = 0; i < ${#authorized_ip[*]}; i +=1))
    do
        ${IPTABLES} -I eth0-root -s ${authorized_ip[$i]}/${authorized_netmask[$i]} -p tcp -m tcp --dport ${vm_port} --tcp-flags FIN,SYN,RST,ACK SYN -j ACCEPT
        [[ ${?} -eq 0 ]] && echo "/sbin/iptables -I eth0-root -s ${authorized_ip[$i]}/${authorized_netmask[$i]} -p tcp -m tcp --dport ${vm_port} --tcp-flags FIN,SYN,RST,ACK SYN -j ACCEPT" >> "${RULES_FILE}"
        ${IPTABLES} -I eth0-root -s $(CreoleGet one_master_ip) -p tcp -m tcp --dport ${vm_port} --tcp-flags FIN,SYN,RST,ACK SYN -j ACCEPT
        [[ ${?} -eq 0 ]] && echo "/sbin/iptables -I eth0-root -s $(CreoleGet one_master_ip) -p tcp -m tcp --dport ${vm_port} --tcp-flags FIN,SYN,RST,ACK SYN -j ACCEPT" >> "${RULES_FILE}"
    done
}


function close_port()
{
    vm_port=$(one_get_port ${1})
    [[ -n "${vm_port}" ]] || return 2
    rule_ids=$(${IPTABLES} -n --line-numbers -L eth0-root | awk "/dpt:${vm_port}/ {print \$1}")
    for rule_id in ${rule_ids}
    do
        ${IPTABLES} -D eth0-root ${rule_id}
        if [[ $? -eq 0 ]]
        then
            sed -i "/--dport ${vm_port}/d" "${RULES_FILE}"
        fi
    done
}


action=${1}
template=${2}

case $action in
    open)
        open_port ${template}
        exit $?
        ;;
    close)
        close_port ${template}
        exit $?
        ;;
    *)
        echo "Unknown action '$action'" >&2
        exit 127
        ;;
esac