#!/bin/bash

# Check if run as root
if [ "$(id -u)" -ne 0 ]; then
    echo "Please run as root or with sudo."
    exit 1
fi

SERVICE_ANSIBLE_PUBKEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIN8oPUWqanJDPGw8wuXSRR3YtgKpiQvWXvkSWROX3f0n service-ansible"

install_packages_apt() {
    apt update
    apt install -y freeipa-client oddjob-mkhomedir chrony
}

install_packages_dnf() {
    dnf -y install freeipa-client oddjob-mkhomedir chrony
}

add_ansible_key() {
    mkdir -p /home/service-ansible/.ssh
    echo "$SERVICE_ANSIBLE_PUBKEY" >> /home/service-ansible/.ssh/authorized_keys
    chown -R service-ansible:service-ansible /home/service-ansible
    chmod 0711 /home/service-ansible
    chmod 0700 /home/service-ansible/.ssh
    chmod 0600 /home/service-ansible/.ssh/authorized_keys
}

set_hostname() {
    current_hostname=$(hostname)
    if [[ $current_hostname != *.* ]]; then
        echo "Current hostname doesn't contain a domain."
        new_hostname="$current_hostname.fjla.net"
        read -p "Set hostname to $new_hostname? (y/n): " set_new
        if [[ $set_new = "y" ]]; then
            hostnamectl set-hostname --static "$new_hostname"
        else
            read -p "Enter hostname (including domain): " new_hostname
            hostnamectl set-hostname --static "$new_hostname"
        fi
    else
        echo "Hostname set to: $current_hostname"
    fi
}

main() {
    if command -v apt &> /dev/null; then
        install_packages_apt
    elif command -v dnf &> /dev/null; then
        install_packages_dnf
    else
        echo "Unsupported package manager."
        exit 1
    fi

    set_hostname
    ipa-client-install --domain=fjla.net --mkhomedir --ntp-pool=time.fjla.net --ssh-trust-dns --subid --all-ip-addresses --enable-dns-updates

    add_ansible_key

    echo "If no errors were encountered, the next Ansible run will complete the configuration of the host"
    echo "Ensure that the host is in the Ansible Hosts file"
}

main