#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

# Google Bash Script Guidelines: All static variables are defined at the top and marked readonly.
readonly REPO_URL="ssh://git@git.jilits.se:2222/JILITS/sysfiles.git"
readonly YADM_DIR="/etc/yadm"
readonly YADM_DATA_DIR="$YADM_DIR/data"
readonly YADM_REPO_PATH="$YADM_DATA_DIR/repo.git"

readonly ROOT_SSH_KEY="/root/.ssh/id_rsa"
readonly ALIASES_FILE="$HOME/.bash_aliases"
readonly -A ALIASES=(
    ["y"]="yadm"
    ["sysyadm"]="sudo yadm --yadm-dir '$YADM_DIR' --yadm-data '$YADM_DATA_DIR'"
    ["s"]="sysyadm"
)

# Function to print messages
function iprint() {
    echo -e "\e[32m[INFO]\e[0m $1"
}
function eprint() {
    echo -e "\e[31m[ERROR]\e[0m $1" >&2
}

# Function to run sysyadm commands
function sysyadm() {
    sudo yadm --yadm-dir "$YADM_DIR" --yadm-data "$YADM_DATA_DIR" "$@"
}

if [ "$EUID" -eq 0 ]; then
    eprint "This script must be run as a non-root user. Exiting."
    exit 1
fi

if ! command -v apt &>/dev/null; then
    eprint "This script is intended for Debian-based systems. Exiting."
    exit 1
fi

iprint "System is Debian-compatible. Proceeding..."

if ! command -v yadm &>/dev/null; then
    iprint "Installing yadm..."
    sudo apt update && sudo apt install -y yadm
else
    iprint "yadm is already installed."
fi

iprint "Ensuring aliases are in $ALIASES_FILE..."

for alias_name in "${!ALIASES[@]}"; do
    alias_cmd="alias $alias_name=\"${ALIASES[$alias_name]}\""
    grep -qxF "$alias_cmd" "$ALIASES_FILE" 2>/dev/null || echo "$alias_cmd" >>"$ALIASES_FILE"
done

iprint "Aliases added. Reloading bash aliases."
# shellcheck disable=SC1090
source "$ALIASES_FILE"

if sudo test -f "$ROOT_SSH_KEY"; then
    iprint "SSH key for root already exists. Skipping key generation."
else
    iprint "Generating SSH key for root..."
    sudo ssh-keygen -t rsa -N "" -f "$ROOT_SSH_KEY"

    iprint "Printing the public SSH key for root:"
    sudo cat "$ROOT_SSH_KEY.pub"

    while true; do
        read -p "Has the SSH key been added to the Git server? (y/n): " CONFIRM
        case $CONFIRM in
        [Yy])
            break
            ;;
        [Nn])
            iprint "Please add the key to the Git server and confirm when done."
            ;;
        *)
            iprint "Please answer y or n."
            ;;
        esac
    done
fi

iprint "Using repository URL: $REPO_URL"

if [ -d "$YADM_REPO_PATH" ]; then
    iprint "Yadm repository already exists at $YADM_REPO_PATH. Skipping initialization and clone."
else
    iprint "Initializing sysyadm with root privileges..."
    sysyadm init -w /

    iprint "Cloning sysyadm repository..."
    sysyadm clone -f -w / "$REPO_URL"
fi

iprint "Running sysyadm alts..."
sysyadm alt

iprint "Running sysyadm bootstrap..."
sysyadm bootstrap

iprint "Script completed successfully."