#!/bin/bash

#   This script is intended to be run from another partition on a bootable USB,
# used to quickly set up a VPN and SSH access to a remote device.
#   It assumes that you are running as the default user, with internet access,
# and have network manager, openvpn, and ssh installed.

#   There should be a OpenVPN configuration and credentials files in the "vpn"
# subdirectory, and an SSH key for a remote server in the "ssh" subdirectory.
# The VPN credentials file should have the username on the first line, and
# password on the second line.

# Time zone
timezone="Region/City"
# VPN details
vpn_login="./vpn/user.auth"
vpn_name="openvpn_server"
vpn_conf="./vpn/$vpn_name.ovpn"
# SSH server details
remote_user="user"
remote_host="10.x.x.x"
# SSH server key details
host_key="ssh_key"
host_key_path="./ssh/$host_key"
host_key_pub="ssh_key.pub"
host_key_pub_path="./ssh/$host_key_pub"

# Determine VPN credentials from file
username="$(sed '1q;d' $vpn_login)"
password="$(sed '2q;d' $vpn_login)"



# Set time zone
timedatectl set-timezone "$timezone"

# Import VPN configuration
nmcli connection import type openvpn file $vpn_conf
# Set password-flags to 0 to prevent keyring prompt
nmcli connection modify $vpn_name +vpn.data "password-flags=0"
# Set username and password
nmcli connection modify $vpn_name +vpn.data "username=$username"
nmcli connection modify $vpn_name vpn.secrets "password=$password"

# Copy server SSH key
mkdir ~/.ssh
cp $host_key_path ~/.ssh/$host_key
cp $host_key_pub_path ~/.ssh/$host_key_pub

# Set up SSH config
cat > ~/.ssh/config << EOF
Host $remote_host
  HostName $remote_host
  User $remote_user
  IdentityFile ~/.ssh/$host_key
EOF



# Connect to VPN and add SSH server to known hosts
nmcli connection up $vpn_name
ssh $remote_user@$remote_host -o StrictHostKeyChecking=no "exit"