#!/usr/bin/bash -ex
#
# This setup script is an unofficial solution designed to deploy QM in
# non-automotive environments like baremetal, desktop, or CICD.
#
# It will install an OS environment by default into
# /usr/lib/qm/rootfs and create a QM containerized environment
# running systemd as PID1 inside.
#

# Globals
SYSTEMCTL_SKIP="N"
REMOVE_QM_ROOTFS="N"
INSTALLDIR="/usr/share/qm"
SETUP_CONFIG_DIR="/etc/qmc.conf.d"
SETUP_SERVICE_DIR="/etc/systemd/system/qm.service.d"
ROOTFS="/usr/lib/qm/rootfs"
RWETCFS="/etc/qm"
RWVARFS="/var/qm"
AGENT_HOSTNAME="$(hostname)"
AGENTCONF="/etc/bluechi/agent.conf.d/agent.conf"
PACKAGES_TO_INSTALL="selinux-policy-targeted podman systemd procps-ng iptables-nft jq hostname"

# RHEL kernel uses iptables-nft, not iptables-legacy, the tool should
# make sure this package is removed.
PACKAGES_TO_REMOVE="iptables-legacy"

CMDLINE_ARGUMENT_LIST=(
  "installdir"
  "rootfs"
  "hostname"
  "rwetcfs"
  "rwvarfs"
  "skip-systemctl"
)

logger() {
    {
     	local log_level="$1"
        local message="$2"
        local NC='\033[0m' # No Color
        local log_col=$NC
    } > /dev/null 2>&1
        case "$log_level" in
            INFO)
                log_col='\033[0;36m' #BLUE
            ;;
            WARNING)
                log_col='\033[1;33m' #YELLOW
            ;;
            ERROR)
                log_col='\033[0;31m' #RED
                ;;
            DEBUG)
                log_col='\033[0;90m' #GREY
                ;;
            SUCCESS)
                log_col='\033[0;32m' #GREEN
            ;;
            *)
              	echo -e "[\033[1;31mERROR\033[0m] Invalid log level: $log_level" >&2
                return 1
            ;;
	esac
  echo -e "[$log_col${log_level}${NC}] $message"
}

root_check() {
    if [ "$(id -u)" -ne 0 ];then
        logger "WARNING" "Please run this script as root"
        exit 1
    fi
}

usage()
{
   echo "This script is an unofficial solution designed to deploy QM in"
   echo "non-automotive environments like baremetal, desktop, or CICD."
   echo
   echo "The setup script will install an OS environment by default into"
   echo "/usr/lib/qm/rootfs and create a QM containerized environment"
   echo "running systemd as PID1 inside."
   echo
   echo "Usage: setup [OPTIONS]"
   echo
   echo "OPTIONS:"
   echo
   echo "--help                Print this message."
   echo "--installdir          qm install directory (default: /usr/share/qm)"
   echo "--rootfs              set rootfs (default: /usr/lib/qm/rootfs)"
   echo "--rwetcfs             set rwetcfs (default: /etc/qm)"
   echo "--rwvarfs             set rwvarfs (default: /var/qm)"
   echo "--skip-systemctl      skip systemctl daemon commands (default: false)"
   echo "--hostname            custom agent hostname to use (default: \$\(hostname\))"
   echo "--remove-qm-rootfs    WARNING: remove qm rootfs created during setup"
   echo
   echo "Example:"
   echo "  $ sudo ./setup --installdir=/usr/share/qm --rootfs=/usr/lib/qm/rootfs"
}

bluechiSetup() {
    ROOTFS=$1
    RWETCFS=$2
    RWVARFS=$3
    setupRW "${ROOTFS}" "${RWETCFS}" "${RWVARFS}"
    if test ! -f "${ROOTFS}${AGENTCONF}"; then
	if test -f "${AGENTCONF}"; then
	    sed -e 's,^NodeName=,NodeName=qm.,g' "${AGENTCONF}" >  "${ROOTFS}${AGENTCONF}"
	fi
    fi
    hostname=$AGENT_HOSTNAME
    if test -f "${ROOTFS}${AGENTCONF}"; then
	sed -e "s,^NodeName=qm.$,NodeName=qm.${hostname},g" \
	    -e "s,^NodeName=$,NodeName=qm.${hostname},g" \
	    -i "${ROOTFS}${AGENTCONF}"
    else
	cat > "${ROOTFS}${AGENTCONF}" <<EOF
[bluechi-agent]
NodeName=qm.${hostname}
EOF
    fi
}

setupRW() {
    ROOTFS=$1
    RWETCFS=$2
    RWVARFS=$3

    mkdir -Z -p "${ROOTFS}/etc" "${ROOTFS}/var"
    mkdir -Z -p "${RWETCFS}" "${RWVARFS}"

    mount --bind "${RWETCFS}" "${ROOTFS}/etc"
    mount --bind "${RWVARFS}" "${ROOTFS}/var"
}

create_rootfs_required_dirs() {
    # List of directories required for rootfs
    directories=(
	    "${ROOTFS}/etc/containers/"
	    "${ROOTFS}/usr/share/containers/selinux/"
	    "${ROOTFS}/etc/selinux/targeted/contexts/files/"
    )

    for dir in "${directories[@]}"; do
        if [ ! -d "$dir" ]; then
            mkdir -Z -p "$dir"
            echo "Created directory: $dir"
        fi
    done

}

validate_qm_installation() {
    files=(
        "${INSTALLDIR}/containers.conf"
        "${INSTALLDIR}/contexts"
        "${INSTALLDIR}/file_contexts"
    )

    for file in "${files[@]}"; do
        if [[ ! -f "$file" ]]; then
            logger "ERROR" "Exiting... '$file' not found. Try reinstall the QM package before continuing."
            exit 1
        fi
    done
}

install() {
    ROOTFS=$1
    RWETCFS=$2
    RWVARFS=$3
    # Persist paths before tools such as qm-storage-settings inspect them.
    write_qmc_configuration
    local requested_rootfs=$ROOTFS requested_etc=$RWETCFS requested_var=$RWVARFS
    read_qmc_paths
    if [[ "$ROOTFS" != "$requested_rootfs" || "$RWETCFS" != "$requested_etc" || "$RWVARFS" != "$requested_var" ]]; then
        echo 'Later qmc configuration overrides the requested setup paths' >&2
        return 1
    fi
    mkdir -p "${RWVARFS}/tmp"
    # shellcheck source=/dev/null
    . /etc/os-release
    setupRW "${ROOTFS}" "${RWETCFS}" "${RWVARFS}"

    EXTRA_FLAG=""
    if [ "$ID" == "fedora" ] && [ "$VERSION_ID" -ge 41 ]; then
        EXTRA_FLAG="--use-host-config"
    fi

    cmd_dnf_install="dnf -y install --releasever=${VERSION_ID} --installroot ${ROOTFS} ${PACKAGES_TO_INSTALL} ${EXTRA_FLAG}"
    echo "$cmd_dnf_install"
    ${cmd_dnf_install}

    if dnf --installroot "${ROOTFS}" list installed "${PACKAGES_TO_REMOVE}" > /dev/null 2>&1; then
        dnf --installroot "${ROOTFS}" remove "${PACKAGES_TO_REMOVE}" -y
    fi

    # check if "${ROOTFS}"/etc/yum.repos.d/
    if test ! -d "${ROOTFS}"/etc/yum.repos.d ; then
        mkdir -p -Z "${ROOTFS}"/etc/yum.repos.d
    fi
    # check if "${ROOTFS}"/etc/yum.repos.d/autosd.repo
    if  test ! -f "${ROOTFS}"/etc/yum.repos.d/autosd.repo; then
       VERSION_ID=$(grep -oP '(?<=^VERSION_ID=)\w+' <<< "$(tr -d '"' < /etc/os-release)")
       cat > "${ROOTFS}"/etc/yum.repos.d/autosd.repo << EOF
[autosd]
name=Automotive-Sig \$releasever
baseurl=https://autosd.sig.centos.org/AutoSD-$VERSION_ID/nightly/repos/AutoSD/compose/AutoSD/\$basearch/os
enabled=1
gpgcheck=0
EOF
    fi

    # Add libkrun & bluechi after rootfs created with repo files in qm
    if [ "$ID" == "centos" ]; then
        # check if "${ROOTFS}"/etc/yum.repos.d/libkrun.repo
        if ! test -f "${ROOTFS}"/etc/yum.repos.d/libkrun.repo; then
            cat > "${ROOTFS}"/etc/yum.repos.d/libkrun.repo << EOF
[copr:copr.fedorainfracloud.org:group_centos-automotive-sig:libkrun]
name=Copr repo for libkrun owned by @centos-automotive-sig
baseurl=https://download.copr.fedorainfracloud.org/results/@centos-automotive-sig/libkrun/centos-stream-\$releasever-\$basearch/
# Keep libkrun and its firmware together instead of mixing in AutoSD builds.
priority=90
type=rpm-md
skip_if_unavailable=True
gpgcheck=1
gpgkey=https://download.copr.fedorainfracloud.org/results/@centos-automotive-sig/libkrun/pubkey.gpg
repo_gpgcheck=0
enabled=1
enabled_metadata=1
EOF
        fi
    fi

    # check if "${ROOTFS}"/etc/yum.repos.d/bluechi.repo
    if ! test -f "${ROOTFS}"/etc/yum.repos.d/bluechi.repo; then
        cat > "${ROOTFS}"/etc/yum.repos.d/bluechi.repo << EOF
[copr:copr.fedorainfracloud.org:group_centos-automotive-sig:bluechi-snapshot]
name=Copr repo for bluechi-snapshot owned by @centos-automotive-sig
baseurl=https://download.copr.fedorainfracloud.org/results/@centos-automotive-sig/bluechi-snapshot/fedora-\$releasever-\$basearch/
type=rpm-md
skip_if_unavailable=True
gpgcheck=1
gpgkey=https://download.copr.fedorainfracloud.org/results/@centos-automotive-sig/bluechi-snapshot/pubkey.gpg
repo_gpgcheck=0
enabled=1
enabled_metadata=1
EOF

        if [ "$ID" == "centos" ]; then
            # set bluchi-repo to centos-stream
            sed -i "s|fedora\-|centos-stream\-|" "${ROOTFS}/etc/yum.repos.d/bluechi.repo"
        fi
    fi

    cmd_dnf_install="dnf -y install --releasever=${VERSION_ID} --setopt=reposdir=${ROOTFS}/etc/yum.repos.d --installroot ${ROOTFS} libkrun crun-krun bluechi-agent ${EXTRA_FLAG}"
    ${cmd_dnf_install}

    dnf -y update --installroot "${ROOTFS}"
    rm -rf "${ROOTFS}"/etc/selinux/targeted/contexts/files/file_contexts/*

    create_rootfs_required_dirs
    validate_qm_installation

    cp "${INSTALLDIR}/containers.conf" "${ROOTFS}/etc/containers/"
    cp "${INSTALLDIR}/contexts" "${ROOTFS}/usr/share/containers/selinux/"
    cp "${INSTALLDIR}/file_contexts" "${ROOTFS}/etc/selinux/targeted/contexts/files/file_contexts"
    bluechiSetup "${ROOTFS}" "${RWETCFS}" "${RWVARFS}"

    if [ "$SYSTEMCTL_SKIP" == "N" ]; then
	unshare --mount-proc -R "${ROOTFS}" -m systemctl enable bluechi-agent.service
    else
	chroot "${ROOTFS}" ln -fs \
	    /usr/lib/systemd/system/bluechi-agent.service \
	    /etc/systemd/system/multi-user.target.wants/bluechi-agent.service
    fi

    "${INSTALLDIR}/qm-storage-settings"
    restorecon -R "${ROOTFS}"
    umount "${ROOTFS}/var" "${ROOTFS}/etc"
}

# Read all paths before any setup or removal side effects. List entries are
# ordered operations; the last operation for a destination decides its source.
read_qmc_paths() {
    local settings
    settings=$(qmc inspect) || return
    ROOTFS=$(jq -er '.rootfs | select(type == "string" and startswith("/"))' <<< "$settings") || return
    RWETCFS=$(jq -er '[.mounts[]? | select(.destination == "/etc")] | last | select(.remove != true) | .source | select(type == "string" and startswith("/"))' <<< "$settings") || return
    RWVARFS=$(jq -er '[.mounts[]? | select(.destination == "/var")] | last | select(.remove != true) | .source | select(type == "string" and startswith("/"))' <<< "$settings") || return
}

validate_setup_paths() {
    local path
    for path in "$ROOTFS" "$RWETCFS" "$RWVARFS"; do
        case "$path" in
            /*) ;;
            *) echo "QM paths must be absolute: $path" >&2; return 1 ;;
        esac
        case "$(realpath -m -- "$path")" in
            /|/usr|/usr/lib|/usr/share|/etc|/var|/home|/root|/run|/tmp|/var/tmp)
                echo "Refusing to use a system directory as QM storage: $path" >&2
                return 1 ;;
        esac
        if [[ "$path" == *$'\n'* || "$path" == *$'\r'* ]]; then
            echo "QM paths must not contain newlines" >&2
            return 1
        fi
    done
}

write_qmc_configuration() {
    validate_setup_paths || return
    local temporary path
    mkdir -p "$SETUP_CONFIG_DIR" "$SETUP_SERVICE_DIR" || return
    temporary=$(mktemp "$SETUP_CONFIG_DIR/.qm-setup.XXXXXX") || return
    if ! jq -n --arg rootfs "$ROOTFS" --arg etc "$RWETCFS" --arg var "$RWVARFS" \
        '{rootfs: $rootfs, mounts: [{source: $etc, destination: "/etc"},
          {source: $var, destination: "/var"},
          {source: ($var + "/tmp"), destination: "/var/tmp"}]}' > "$temporary"; then
        rm -f "$temporary"
        return 1
    fi
    chmod 0644 "$temporary"
    mv -f "$temporary" "$SETUP_CONFIG_DIR/50-qm-setup.conf"
    {
        printf '[Unit]\nRequiresMountsFor=\n'
        for path in "$ROOTFS" "$RWETCFS" "$RWVARFS"; do
            path=${path//\\/\\\\}
            path=${path//\"/\\\"}
            path=${path//%/%%}
            printf 'RequiresMountsFor="%s"\n' "$path"
        done
    } > "$SETUP_SERVICE_DIR/50-qm-setup.conf"
}

remove_qm_rootfs() {
    # Resolve errors and unsafe paths before stopping services or removing data.
    read_qmc_paths || return
    validate_setup_paths || return
    if [ "$SYSTEMCTL_SKIP" == "N" ]; then
        systemctl stop qm.service || return
    fi
    local target
    while IFS= read -r target; do
        case "$target" in
            "$ROOTFS"|"$ROOTFS"/*|"$RWETCFS"|"$RWETCFS"/*|"$RWVARFS"|"$RWVARFS"/*)
                umount -- "$target" || return ;;
        esac
    done < <(findmnt -rn -o TARGET | sort -r)
    # Remove the configured tree itself, never its parent directory.
    rm -rf --one-file-system -- "$ROOTFS" "$RWETCFS" "$RWVARFS"
}

main() {
# read command line arguments
opts=$(getopt \
  --longoptions "$(printf "help,skip-systemctl,remove-qm-rootfs,%s:," "${CMDLINE_ARGUMENT_LIST[@]}")" \
  --name "$(basename "$0")" \
  --options "" \
  -- "$@"
)

eval set --"${opts}"

# main()
root_check
read_qmc_paths || return

while [[ $# -gt 0 ]]; do
  case "$1" in
    --installdir)
      INSTALLDIR="${2}"
      shift 2
      ;;
    --rootfs)
      ROOTFS="${2}"
      shift 2
      ;;
    --rwetcfs)
      RWETCFS="${2}"
      shift 2
      ;;
    --rwvarfs)
      RWVARFS="${2}"
      shift 2
      ;;
    --skip-systemctl)
      SYSTEMCTL_SKIP="Y"
      shift
      ;;
    --hostname)
      AGENT_HOSTNAME="${2}"
      shift 2
      ;;
    --remove-qm-rootfs)
      REMOVE_QM_ROOTFS="Y"
      shift 2
      ;;
    --help)
      usage
      exit 1
      ;;
    *)
      break
      ;;
  esac
done

# Figure out the options, execute setup
echo "setup has started..."
echo  "  * rootfs: ${ROOTFS}"
echo  "  * rwetcfs: ${RWETCFS}"
echo  "  * rwvarfs: ${RWVARFS}"
echo  "  * install dir: ${INSTALLDIR}"
echo  "  * skip-systemctl: ${SYSTEMCTL_SKIP}"
echo  "  * remove-qm-rootfs: ${REMOVE_QM_ROOTFS}"
echo  "  * agent hostname: ${AGENT_HOSTNAME}"
echo

if [ "${REMOVE_QM_ROOTFS}" == "Y" ]; then
    remove_qm_rootfs
    return $?
fi


case "$1" in
    bluechi-agent)
	rm -f "${ROOTFS}${AGENTCONF}"
	bluechiSetup "${ROOTFS}" "${RWETCFS}" "${RWVARFS}"
	;;
    *)

    if [ "$SYSTEMCTL_SKIP" == "N" ]; then
	    if systemctl is-active --quiet "qm.service" ; then
		systemctl stop qm.service
	    fi
    fi

	install "${ROOTFS}" "${RWETCFS}" "${RWVARFS}"

    if [ "$SYSTEMCTL_SKIP" == "N" ]; then
	    systemctl daemon-reload
        systemctl enable --now qm.service || {
            logger "ERROR" "'systemctl start qm.service' has failed, see details below";
            set +x
            logger "DEBUG" "$(journalctl --no-pager -xu qm.service)"
            set -x
            exit 1;
        }
        if [ "$(systemctl is-active qm.service)" != "active" ]; then
            logger "WARNING" "QM service is inactive, see details below:";
            set +x
            logger "DEBUG" "$(journalctl --no-pager -xu qm.service)"
            set -x
            exit 1
        fi
    fi
    if [ "$SYSTEMCTL_SKIP" == "Y" ]; then
        # Enabling is an offline filesystem operation; no system manager needed.
        local wants_dir="${SETUP_SERVICE_DIR%/qm.service.d}/default.target.wants"
        mkdir -p "$wants_dir"
        ln -sfn /usr/lib/systemd/system/qm.service "$wants_dir/qm.service"
    fi
    logger "SUCCESS" "Setup complete";
	;;
esac

}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
    main "$@"
fi
