#!/bin/bash
######################################################################
#Copyright (C) 2023 Kris Occhipinti
#https://filmsbykris.com
#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 version 3 of the License.
#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 .
######################################################################
which upnpc >/dev/null || sudo apt install miniupnpc
function getinput(){
read -p "Internal Port: " in_port
[[ $in_port ]] || exit
read -p "Extertnal Port: " ext_port
[[ $ext_port ]] || exit
ip="$(ip a|grep inet|grep "[0-9].[0-9].[0-9].[0-9]"|awk '{print $2}'|cut -d\/ -f1|fzf --prompt "Internal IP: ")"
[[ $ip ]] || exit
openport
}
function openport(){
[[ $in_port ]] || in_port=$2
[[ $ext_port ]] || ext_port=$3
[[ $ip ]] || ip=$1
echo -n "Opening port $ext_port to port $in_port on $ip..."
router="$(ip r | grep default | cut -d " " -f 3)"
echo -n "."
gateway="$(upnpc -l|grep 'desc:'|awk '{print $2}')"
echo "."
#open port
echo ": $(date +%s):0;upnpc -u $gateway -a $ip $in_port $ext_port tcp" >> $HOME/.zsh_history
echo ": $(date +%s):0;upnpc -u $gateway -d $ext_port tcp" >> $HOME/.zsh_history
upnpc -u $gateway -a $ip $in_port $ext_port tcp
exit
}
function closeport(){
command="$(grep upnpc ~/.zsh_history|grep '\-d'|grep -v 'grep'|cut -d\; -f2|fzf)"
echo "Closing Port"
$command
exit
}
[[ "$1" == "close" ]] && closeport
[[ $# == 3 ]] && openport $*
getinput