#!/bin/bash

TMP_FOLDER=/tmp/resilioagent
JAIL_NAME=resilioagentjail
JAIL_EXE="iocage exec $JAIL_NAME"

JAIL_SCRIPT=https://internal.resilio.com/support/freenas/jailscript_v3.sh
JAIL_SCRIPT_PATH=$TMP_FOLDER/jailscript.sh
FREEBSD_VERSION=12.2-RELEASE

while getopts s:p: flag
do
  case "${flag}" in
    s) SERVER=${OPTARG};;
    p) ZPOOL=${OPTARG};;
  esac
done

echo "Server IP: $SERVER";
echo "ZPool: $ZPOOL";

[ -z $ZPOOL ] || iocage activate $ZPOOL
iocage create -r $FREEBSD_VERSION -n $JAIL_NAME
iocage set vnet=on $JAIL_NAME
iocage set nat=on $JAIL_NAME
iocage start $JAIL_NAME
iocage set boot=1 $JAIL_NAME
iocage set nat_forwards=tcp\(3839:3839\),udp\(3839:3839\) $JAIL_NAME

$JAIL_EXE pkg install -y wget dbus
$JAIL_EXE dbus-uuidgen --ensure
$JAIL_EXE rm -r $TMP_FOLDER
$JAIL_EXE mkdir $TMP_FOLDER
$JAIL_EXE wget -O $JAIL_SCRIPT_PATH $JAIL_SCRIPT
$JAIL_EXE chmod +x $JAIL_SCRIPT_PATH
$JAIL_EXE $JAIL_SCRIPT_PATH -s $SERVER
