#!/bin/sh
# -*- mode: sh; sh-shell: sh -*-
#
# Copyright (C) 2018 Paul Wouters <pwouters@redhat.com>
# Copyright (C) 2022 Andrew Cagney
#
# 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 2 of the License, or (at your
# option) any later version.  See <https://www.gnu.org/licenses/gpl2.txt>.
#
# 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.

set -u
#set -e

if test $# -lt 4 ; then
    echo "Usage: QNAME TTL IP RRDATA" 1>&2
    exit 1
fi

# Get my %defaultroute (gateway) IP address.
myip=$(ipsec showroute --gateway 8.8.8.8)

qname=$1 ; shift
ttl=$1 ; shift
ip=$1 ; shift

# Remainder of parameters are quoted DNS RRs, iterate over each
# breaking it down.

for rr in "$@" ; do
    # reset args to
    set -- ${rr}
    if test $# -lt 5 ; then
	echo "ignoring short rr record: $@" 1>&2
	exit 1
    fi
    gwprec=$1 ; shift
    gwtype=$1 ; shift
    gwalg=$1 ; shift
    gwid=$1 ; shift
    pubkey=$1 ; shift

    echo "processing an IPSECKEY record for Opportunistic IPsec to ${qname}(${ip})"
    ipsec whack --keyid "${ip}" --addkey --pubkeyrsa 0s"${pubkey}"
    ipsec whack --keyid @"${qname}" --addkey --pubkeyrsa 0s"${pubkey}"
done

# done injecting all IPSECKEY records into pluto - try actual OE now
ipsec whack --oppohere "${myip}" --oppothere "${ip}"

#cmdoeqname = "ipsec whack --oppohere %s --oppothere %s"%(myip, qname)
#ret, output = commands.getstatusoutput(cmdoeqname)
ipsec whack --trafficstatus
