#!/bin/sh

apt-get update

# Install necessary packages
apt-get install -y debconf-utils
apt-get install -y ca-certificates
apt-get install -y wget
apt-get install -y git
apt-get install -y python3
apt-get install -y p7zip-full unzip
apt-get install -y iptables ebtables
apt-get install -y curl
apt-get install -y lsb-release
apt-get install -y gpg
apt-get install -y jq

# Adjust user groups
adduser vsoc-01 kvm
adduser vsoc-01 render
adduser vsoc-01 video

apt -o Apt::Get::Assume-Yes=true -o APT::Color=0 -o DPkgPM::Progress-Fancy=0 update

# Install kernel
DEBIAN_DISTRIBUTION="$(lsb_release -c -s)"
DEBIAN_SNAPSHOT_DIR="/root/debian-snapshot"
#apt-get install -y '^linux-image-6.1.*aosp14-linaro.*' '^linux-headers-6.1.*aosp14-linaro.*'
has_backports=$(apt-cache policy | grep "${DEBIAN_DISTRIBUTION}-backports")
# Enable ARM64 nested virtualization (KVM NV2).
#
# Note that any VHE host honors the flag, FEAT_NV2 or not. Without FEAT_NV2 KVM
# falls back to normal VHE operation. Without a GICv3-class vGIC the flag is
# fatal - KVM initialization fails and /dev/kvm never appears.
sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT=\"\(.*\)\"/GRUB_CMDLINE_LINUX_DEFAULT=\"\1 kvm-arm.mode=nested\"/' /etc/default/grub
if [ x"$has_backports" != x"" ]; then
    apt install -y -t "${DEBIAN_DISTRIBUTION}-backports" linux-headers-arm64
    apt install -y -t "${DEBIAN_DISTRIBUTION}-backports" linux-image-arm64
else
    KERNEL_ABI="6.18.15+deb13-arm64"
    KERNEL_DEB_VERSION="6.18.15-1~bpo13+1"
    apt-get -o Dir::Etc::SourceParts="${DEBIAN_SNAPSHOT_DIR}" -o Acquire::Retries=5 update
    apt-get install -y -o Dir::Etc::SourceParts="${DEBIAN_SNAPSHOT_DIR}" -o Acquire::Retries=5 \
        "linux-image-${KERNEL_ABI}=${KERNEL_DEB_VERSION}" \
        "linux-headers-${KERNEL_ABI}=${KERNEL_DEB_VERSION}" || exit 1
fi

# Install nVidia or AMD GPU driver
nvidia_gpu=$(lspci | grep -i nvidia)
amd_gpu=$(lspci | grep VGA | grep AMD)
if [ x"$amd_gpu" != x"" ]; then
    # # Install amd firmware
    # if [ x"$has_backports" != x"" ]; then
    #     apt-get install -y -t ${DEBIAN_DISTRIBUTION}-backports firmware-amd-graphics
    # else
    #     apt-get install -y firmware-amd-graphics
    # fi
    # sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT=\"\(.*\)\"/GRUB_CMDLINE_LINUX_DEFAULT=\"\1 amdgpu.runpm=0 amdgpu.dc=0\"/' /etc/default/grub
    # dpkg-reconfigure -fnoninteractive grub-efi-arm64
    echo "AMD GPU detected — skipping GPU driver installation."
elif [ x"$nvidia_gpu" != x"" ]; then
    # Install nvidia driver
    if [ x"$has_backports" != x"" ]; then
        DEBIAN_FRONTEND=noninteractive apt-get install -y -t "${DEBIAN_DISTRIBUTION}-backports" -q --force-yes nvidia-kernel-dkms
        DEBIAN_FRONTEND=noninteractive apt-get install -y -t "${DEBIAN_DISTRIBUTION}-backports" -q --force-yes nvidia-driver
        DEBIAN_FRONTEND=noninteractive apt-get install -y -t "${DEBIAN_DISTRIBUTION}-backports" -q --force-yes firmware-misc-nonfree
    else
        NVIDIA_DEB_VERSION="550.163.01-4~bpo13+1"
        apt-get -o Dir::Etc::SourceParts="${DEBIAN_SNAPSHOT_DIR}" -o Acquire::Retries=5 update
        DEBIAN_FRONTEND=noninteractive apt-get install -y -q -o Dir::Etc::SourceParts="${DEBIAN_SNAPSHOT_DIR}" \
            -o Acquire::Retries=5 -t ${DEBIAN_DISTRIBUTION}-backports \
            "nvidia-open-kernel-dkms=${NVIDIA_DEB_VERSION}" \
            "nvidia-driver=${NVIDIA_DEB_VERSION}" || exit 1
        DEBIAN_FRONTEND=noninteractive apt-get install -y -q firmware-misc-nonfree
        apt-mark hold nvidia-open-kernel-dkms nvidia-driver
    fi
fi
# End of Install kernel

# Regenerate grub.cfg: the kernel postinst's update-grub hook only runs when a
# kernel package is actually configured, so a no-op install above would leave
# the nested-virt cmdline out of the boot menu.
if [ -e /boot/grub/grub.cfg ]; then
    update-grub || exit 1
fi

# Install android cuttlefish packages
#DEPLOY_CHANNEL=
#DEPLOY_VERSION=
curl -fsSL --retry 7 --retry-all-errors https://us-apt.pkg.dev/doc/repo-signing-key.gpg -o /etc/apt/trusted.gpg.d/artifact-registry.asc
chmod a+r /etc/apt/trusted.gpg.d/artifact-registry.asc
if [ x"${DEPLOY_CHANNEL}" = x"nightly" ]; then
    echo "deb https://us-apt.pkg.dev/projects/android-cuttlefish-artifacts android-cuttlefish-nightly main" \
        | tee -a /etc/apt/sources.list.d/artifact-registry.list
elif [ x"${DEPLOY_CHANNEL}" = x"unstable" ]; then
    echo "deb https://us-apt.pkg.dev/projects/android-cuttlefish-artifacts android-cuttlefish-unstable main" \
        | tee -a /etc/apt/sources.list.d/artifact-registry.list
else
    echo "deb https://us-apt.pkg.dev/projects/android-cuttlefish-artifacts android-cuttlefish main" \
        | tee -a /etc/apt/sources.list.d/artifact-registry.list
fi

apt-get update

if [ x"${DEPLOY_CHANNEL}" = x"stable" ]; then
    apt-get install -y cuttlefish-base="${DEPLOY_VERSION}" cuttlefish-user="${DEPLOY_VERSION}" cuttlefish-orchestration="${DEPLOY_VERSION}" -t android-cuttlefish
    apt-mark hold cuttlefish-base cuttlefish-user cuttlefish-orchestration
elif [ x"${DEPLOY_CHANNEL}" != x"" ]; then
    apt-get install -y cuttlefish-base="${DEPLOY_VERSION}" cuttlefish-user="${DEPLOY_VERSION}" cuttlefish-orchestration="${DEPLOY_VERSION}" -t android-cuttlefish-"${DEPLOY_CHANNEL}"
    apt-mark hold cuttlefish-base cuttlefish-user cuttlefish-orchestration
else
    apt-get install -y cuttlefish-base cuttlefish-user cuttlefish-orchestration -t android-cuttlefish
fi

adduser vsoc-01 cvdnetwork

# Install gigabyte package
if [ x"${DEPLOY_CHANNEL}" != x"" ]; then
    apt -o Apt::Get::Assume-Yes=true -o APT::Color=0 -o DPkgPM::Progress-Fancy=0 -o Acquire::Retries=5 install cuttlefish-integration-gigabyte-arm64="${DEPLOY_VERSION}"
    apt-mark hold cuttlefish-integration-gigabyte-arm64
else
    apt -o Apt::Get::Assume-Yes=true -o APT::Color=0 -o DPkgPM::Progress-Fancy=0 -o Acquire::Retries=5 install cuttlefish-integration-gigabyte-arm64
fi

# Extra tools
cd /root
git clone https://github.com/matthuisman/gdrivedl.git
cd -

# Use iptables-legacy
update-alternatives --set iptables /usr/sbin/iptables-legacy

# Install network manager
apt-get install -y network-manager

# Network-manager workaround
rm -f '/etc/NetworkManager/system-connections/Wired connection 1'

# Install Docker container
# Add Docker's official GPG key:
apt-get update
curl -fsSL --retry 7 --retry-all-errors https://download.docker.com/linux/debian/gpg -o /etc/apt/trusted.gpg.d/docker.asc
chmod a+r /etc/apt/trusted.gpg.d/docker.asc

# Add the repository to Apt sources:
echo \
  "deb [arch=$(dpkg --print-architecture)] https://download.docker.com/linux/debian $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
  tee /etc/apt/sources.list.d/docker.list > /dev/null
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y -q docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
usermod -aG docker vsoc-01

# Install nvidia-container-toolkit
curl -fsSL --retry 7 --retry-all-errors https://nvidia.github.io/libnvidia-container/gpgkey | gpg --dearmor -o /etc/apt/trusted.gpg.d/nvidia-container-toolkit-keyring.gpg \
&& curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \
  tee /etc/apt/sources.list.d/nvidia-container-toolkit.list
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y  -q --force-yes nvidia-container-toolkit
