#!/bin/env bash

# Prepended to this automatically are the following:
#SERVER=
#HOSTNAME=
#ROLES=
#REPO_URL=
#BRANCH=
#SSH_SECRET_ID=

if ! curl -fLs -m 5 http://169.254.169.254/latest/dynamic/instance-identity/document | grep instanceId; then
    echo "This should be run on AWS instances, not locally."
    exit 1
fi

set -e
set -x

# Set the hostname early
echo "$HOSTNAME" >/etc/hostname
hostname "$HOSTNAME"
sed -i "s/localhost$/localhost $HOSTNAME $SERVER/" /etc/hosts

# Delete the ubuntu user
userdel ubuntu

# Make sure root doesn't have a password
passwd -d root

# Allow root logins
sed -i 's/disable_root: true/disable_root: false/' /etc/cloud/cloud.cfg

# Ensure all apt updates (here and in the installer) are non-interactive
export DEBIAN_FRONTEND=noninteractive

# Dependencies to install AWS CLI
(
    apt-get -qy update
    apt-get -qy -o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold" upgrade
    apt-get -qy install jq unzip curl
    apt-get -qy autoclean
)

# The following line gets subbed in with the contents of bootstrap-awscli.sh
AWS=

# Set up AWS so we can use the role credentials we were started with, which give secrets access
mkdir -p /root/.aws
cat >/root/.aws/config <<EOF
[default]
region = us-east-1
output = text
credential_source = Ec2InstanceMetadata
EOF

# Set up public keys for root, so we can fetch the repo; this is a
# function so we do can it again later with the zulip user
function install_keys() {
    USERNAME="$1"
    SSHDIR="$(getent passwd "$USERNAME" | cut -d: -f6)/.ssh"
    KEYDATA="$($AWS --output text \
        secretsmanager get-secret-value \
        --secret-id "$SSH_SECRET_ID" \
        --query SecretString)"
    mkdir -p "$SSHDIR"
    for KEYFILE in $(echo "$KEYDATA" | jq -r 'keys[]'); do
        echo "$KEYDATA" | jq -r ".[\"$KEYFILE\"]" | base64 -d >"$SSHDIR/$KEYFILE"
        if [[ "$KEYFILE" != *".pub" ]]; then
            chmod 600 "$SSHDIR/$KEYFILE"
        fi
    done
    chown -R "$USERNAME:$USERNAME" "$SSHDIR"
}
install_keys root

# Provide GitHub known_hosts setup; you can verify against fingerprints at
# https://docs.github.com/en/github/authenticating-to-github/githubs-ssh-key-fingerprints
# via `ssh-keygen -lf`
cat >/root/.ssh/known_hosts <<EOF
github.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==
EOF

cd /root
git clone "$REPO_URL" zulip -b "$BRANCH"
git -C zulip checkout "$BRANCH"

(
    VIRTUALENV_NEEDED=$(if echo "$ROLES" | grep -q app_frontend; then echo -n yes; else echo -n no; fi)
    export VIRTUALENV_NEEDED
    export PUPPET_CLASSES="$ROLES"
    export APT_OPTIONS="-o Dpkg::Options::=--force-confnew"
    /root/zulip/scripts/setup/install \
        --self-signed-cert \
        --no-init-db
)

install_keys zulip

reboot
