#!/bin/bash
dpkg-reconfigure openssh-server
create_user_from_shared_names_list () {
    my_last_octet=$1
    my_username_pwhash=$(sed -n "${my_last_octet}{p;q}" /etc/workshopnames.yml)
    my_username="${my_username_pwhash%%:*}"
    my_pwhash_pwd="${my_username_pwhash#*: }"
    my_pwhash=${my_pwhash_pwd%%,*}
    my_pwd=${my_pwhash_pwd#*,}
    useradd -m ${my_username} -p "${my_pwhash}" -s /bin/bash
    # su - ${my_username} -c 'mkdir -p .ssh'
    su - ${my_username} -c "echo 'alias fireworks=\"fireworks.sh Fireworks\"' >> ~/.bash_aliases"
    echo "$my_pwd" > /home/${my_username}/PASSWORD
}


case $(hostname) in 
    jumphost1)
    useradd -m devops -s /bin/bash
    # the "westbound" interface gw<->jumphost1
    ip addr replace dev eth0 172.16.202.33/31
    ip route replace 192.168/16 via 172.16.202.32

    # the "southbound" interface towards webserver1 (also named webserver, defaults to ipv4 in /etc/hosts)
    ip addr replace dev eth1 172.16.200.1/24
    ip addr replace dev eth1 fd4c:00a6:b6a7::ae/127

    # eastbound jumphost1-eth2<->eth0-jumphost2
    ip addr replace dev eth2 172.16.202.34/31
    printf "172.16.202.35\tjumphost2\n" >> /etc/hosts
    printf "172.16.200.11\twebserver webserver-ipv4 webserver1 webserver1-ipv4\n" >> /etc/hosts
    printf "fd4c:00a6:b6a7::af\twebserver-ipv6 webserver1-ipv6\n" >> /etc/hosts

    for user_no in $(seq 10 200); do
        create_user_from_shared_names_list ${user_no}
    done
    ;;

    jumphost2)
    # jumphost2 will have a forward-only authorized keys
    # cert-authority,no-pty,command="" <key>
    useradd -m dbadmin
    mkdir -p /home/dbadmin/.ssh
    echo "cert-authority,no-pty,command=\"\" " > /home/dbadmin/.ssh/authorized_keys
    # the "westbound" interface jumphost1-eth2<->eth0-jumphost2
    ip addr replace dev eth0 172.16.202.35/31

    # the "southbound" interface towards webserver2 (which I want to name "webserver" as well in order to confuse known_hosts. Also, defaults to ipv6 in /etc/hosts)
    ip addr replace dev eth1 172.16.201.1/24
    ip addr replace dev eth1 fd4c:00a6:b6a7::ce/127

    printf "172.16.202.34\tjumphost1\n" >> /etc/hosts
    printf "fd4c:00a6:b6a7::cf\twebserver webserver-ipv6 webserver2 webserver2-ipv6\n" >> /etc/hosts
    printf "172.16.201.12\twebserver-ipv4 webserver2-ipv4\n" >> /etc/hosts
    ;;
esac

# launch dnsmasq (automatically backgrounds)

/usr/sbin/sshd -D
