#!/bin/bash
## Create new Linux contanier at a proxmox host

DMZKEYFILE=$(echo -n ~)"/.ssh/dmz"
USER=$(cut -d" " -f3 $DMZKEYFILE.pub | cut -d "@" -f1)
USEREMAIL=$(cut -d" " -f3 $DMZKEYFILE.pub)

PROXMOXHOST=$1
CTHOST=$2

GENPASS=$( echo $(shuf ../shared/english.txt | head) | sed "s/ //g")

if [[ -z "$PROXMOXHOST" ]]; then 
	echo "Set Proxmox Host"
        exit 1
fi

if [[ -z "$CTHOST" ]]; then 
	echo "Set CT hostname"
        exit 1
fi

if [[ -z "$GENPASS" ]]; then 
	echo "Set CT password"
        exit 1
fi

ssh-add -t 600 $DMZKEYFILE
torsocks scp ./remotecmd $PROXMOXHOST:/root/ctcreate.sh
torsocks scp $DMZKEYFILE.pub $PROXMOXHOST:/root/.ssh/$USER.pub

torsocks ssh $PROXMOXHOST "chmod +x /root/ctcreate.sh; /root/ctcreate.sh $CTHOST $GENPASS $USER" >> cmdoutput.txt

CREDS=$( tail -3 cmdoutput.txt)

rm cmdoutput.txt

printf "$CREDS\n" | gpg -e -r $USEREMAIL --output $CTHOST.gpg

CTIP=$(printf "$CREDS" | head -1 | cut -d'@' -f 2)

echo "Host dmzkrov"$CTHOST >> ~/.ssh/autoconfig
echo "  Hostname "$CTIP >> ~/.ssh/autoconfig
echo "  ProxyJump dmzkrovtor12" >> ~/.ssh/autoconfig
echo "  User root" >> ~/.ssh/autoconfig
echo "  IdentityFile "$DMZKEYFILE >> ~/.ssh/autoconfig
echo "  PasswordAuthentication no" >> ~/.ssh/autoconfig

ssh -R $CTIP
torsocks scp ./newct dmzkrov$CTHOST:/root/newct.sh
torsocks ssh dmzkrov$CTHOST "bash newct.sh; rm newct.sh"
torsocks ssh dmzkrov$CTHOST