#!/usr/bin/env bash

# {{ ansible_managed }}

export HOME=/root

# Prevent service startup while we are working in chroot
cat > /usr/sbin/policy-rc.d <<EOF
#!/bin/sh
echo "All runlevel operations denied by policy" >&2
exit 101
EOF
chmod +x /usr/sbin/policy-rc.d

## Move APT proxy configuration to the same location that debops.apt uses to configure APT proxy settings.
mv /etc/apt/apt.conf /etc/apt/apt.conf.d/000apt-cacher-ng-proxy || true

GRUB_PRESEED="{{ preseed__grub_preseed | bool | lower }}"
GRUB_TIMEOUT="{{ preseed__grub_timeout | string }}"
read -r -a GRUB_KERNEL_OPTIONS <<< "{{ preseed__grub_kernel_options | join(' ') }}"

# Setup grub, cgroup, LXC
if [ "${GRUB_PRESEED}" = "true" ] ; then
    if [ -r "/etc/default/grub" ]; then
        dpkg-divert --quiet --local --divert /etc/default/grub.dpkg-divert --rename /etc/default/grub
        cp /etc/default/grub.dpkg-divert /etc/default/grub
        perl -pi -e "s,^GRUB_TIMEOUT=5$,GRUB_TIMEOUT=${GRUB_TIMEOUT}," /etc/default/grub
        if [[ "${GRUB_KERNEL_OPTIONS[*]}" ]] ; then
            perl -pi -e "s,GRUB_CMDLINE_LINUX=\"(.*)\"$,GRUB_CMDLINE_LINUX=\"\$1 ${GRUB_KERNEL_OPTIONS[*]}\"," /etc/default/grub
        fi
        update-grub
    fi
fi

SALT_SETUP="{{ (item.salt | d(preseed__salt)) | bool | lower }}"
SALT_UPSTREAM_APT_REPO="{{ preseed__salt_upstream_repository }}"
SALT_UPSTREAM_APT_KEY_URL="{{ preseed__salt_apt_key_url }}"
read -r -a SALT_PACKAGES <<< "{{ preseed__salt_packages | join(' ') }}"
SALT_OPTIONS="{{ item.salt_options | d(preseed__salt_options) }}"

# Configure Salt APT repository
if [ "${SALT_SETUP}" = "true" ] ; then
    echo "${SALT_UPSTREAM_APT_REPO}" >> /etc/apt/sources.list.d/salt.list
    wget --no-proxy -q -O- "${SALT_UPSTREAM_APT_KEY_URL}" | apt-key add -
    apt-get update

    # Install Salt packages
    apt-get -yq install "${SALT_PACKAGES[@]}"

    # Configuration for Salt minion
    if [ -n "${SALT_OPTIONS}" ] ; then
        cat > /etc/salt/minion.d/ansible.conf <<EOF
${SALT_OPTIONS}
EOF
    fi
fi

ADMIN_SETUP="{{ (item.admin | d(preseed__admin)) | bool | lower }}"
ADMIN_SYSTEM="{{ (item.admin | d(preseed__admin_system)) | bool | lower }}"
read -r -a ADMIN_GROUPS <<< "{{ (item.admin_groups | d(preseed__admin_groups)) | join(' ') }}"
SUDO_SETUP="{{ (item.sudo | d(preseed__sudo)) | bool | lower }}"

if [ "${ADMIN_SETUP}" = "true" ] ; then
    preseed__admin_name="{{ item.admin_name | default(preseed__admin_name) }}"
    preseed__admin_groups_useradd="{{ (item.admin_groups | default(preseed__admin_groups)) | join(',') }}"
    preseed__admin_comment="{{ item.admin_comment | default(preseed__admin_comment | default('System Administrator')) }}"
    preseed__admin_shell="{{ item.admin_shell | default(preseed__admin_shell | default('/bin/bash')) }}"

    if [ "${ADMIN_SYSTEM}" = "true" ] ; then
        preseed__admin_home="{{ item.admin_system_home | default(preseed__admin_system_home | default('/var/local/' + item.admin_name | default(preseed__admin_name))) }}"
    elif [ "${ADMIN_SYSTEM}" = "false" ] ; then
        preseed__admin_home="{{ item.admin_home | default(preseed__admin_home | default('/home/' + item.admin_name | default(preseed__admin_name))) }}"
    fi

    preseed__admin_home_group="{{ preseed__admin_home_group }}"
    preseed__admin_home_mode="{{ preseed__admin_home_mode }}"
    preseed__sudo_group="{{ preseed__sudo_group }}"

    # Create required system groups if not present
    if [[ "${ADMIN_GROUPS[*]}" ]] ; then
        for system_group in "${ADMIN_GROUPS[@]}" ; do
            getent group "${system_group}" > /dev/null || groupadd --system "${system_group}"
        done
    fi

    if [ "${SUDO_SETUP}" = "true" ] ; then
        # Configure admin group in sudo
        echo "%${preseed__sudo_group} ALL = (ALL:ALL) NOPASSWD: SETENV: ALL" > "/etc/sudoers.d/${preseed__sudo_group}"
        chmod 0440 "/etc/sudoers.d/${preseed__sudo_group}"
    fi

    # Create administrator account
    if [ "${ADMIN_SYSTEM}" = "true" ] ; then
        if ! getent passwd "${preseed__admin_name}" ; then
            useradd --system --user-group --groups "${preseed__admin_groups_useradd}" --create-home --home "${preseed__admin_home}" --comment "${preseed__admin_comment}" --shell "${preseed__admin_shell}" "${preseed__admin_name}"
            chgrp "${preseed__admin_home_group}" "${preseed__admin_home}"
            chmod "${preseed__admin_home_mode}" "${preseed__admin_home}"
        fi
    elif [ "${ADMIN_SYSTEM}" = "false" ] ; then
        if ! getent passwd "${preseed__admin_name}" ; then
            adduser --disabled-password --home "${preseed__admin_home}" --gecos "${preseed__admin_comment}" --shell "${preseed__admin_shell}" "${preseed__admin_name}"
            chgrp "${preseed__admin_home_group}" "${preseed__admin_home}"
            chmod "${preseed__admin_home_mode}" "${preseed__admin_home}"

            if [[ "${ADMIN_GROUPS[*]}" ]] ; then
                for system_group in "${ADMIN_GROUPS[@]}" ; do
                    adduser "${preseed__admin_name}" "${system_group}"
                done
            fi
        fi
    fi

    # shellcheck disable=SC1117
    preseed__admin_sshkeys="{{ (item.admin_sshkeys|d([]) + preseed__admin_sshkeys|d([])) | join('\n') }}"

    if [ -n "${preseed__admin_sshkeys}" ] ; then

        # shellcheck disable=SC2174
        mkdir -p -m 700 /root/.ssh
        echo "${preseed__admin_sshkeys}" > /root/.ssh/authorized_keys

        if [ "${ADMIN_SETUP}" = "true" ] ; then
            admin_home="$(getent passwd "${preseed__admin_name}" | cut -d: -f6)"
            # shellcheck disable=SC2174
            mkdir -p -m 700 "${admin_home}/.ssh"
            touch "${admin_home}/.ssh/authorized_keys"
            echo "${preseed__admin_sshkeys}" >> "${admin_home}/.ssh/authorized_keys"
            chown -R "${preseed__admin_name}:${preseed__admin_name}" "${admin_home}/.ssh"
        fi
    fi
fi

readarray -t postinst_commands << EOF
{% if preseed__debian_postinst_commands is defined and preseed__debian_postinst_commands %}
{{ preseed__debian_postinst_commands }}
{% endif %}
{% if item.postinst_commands is defined and item.postinst_commands %}
{{ item.postinst_commands }}
{% endif %}
EOF

if [[ "${postinst_commands[*]}" ]] ; then
    for index in "${!postinst_commands[@]}" ; do
        # shellcheck disable=SC2086
        eval ${postinst_commands[${index}]}
    done
fi

# Unlock service startup
rm -rf /usr/sbin/policy-rc.d
