#!/bin/bash

# 检查是否以 root 用户身份执行脚本
check_root() {
    if [ "$EUID" -ne 0 ]; then
        echo "此脚本需要以 root 权限执行。"
	bash
        exit 1
    fi
}

# 安装必要的软件包
install_packages() {
    apt update -y && apt install -y gnupg2 wget || { echo "安装必要软件包失败"; exit 1; }
}

# 添加 GPG 密钥
add_gpg_key() {
    local version_id
    source /etc/os-release
    version_id=$VERSION_ID
    
    local key_url="http://downloadcontent.opensuse.org/repositories/home:/alvistack/Debian_${version_id}/Release.key"
    wget -qO- "$key_url" | gpg --dearmor | tee /etc/apt/trusted.gpg.d/alvistack.gpg >/dev/null || { echo "添加 GPG 密钥失败"; exit 1; }
}

# 添加 APT 仓库
add_apt_repo() {
    local version_id
    source /etc/os-release
    version_id=$VERSION_ID
    
    echo "deb http://downloadcontent.opensuse.org/repositories/home:/alvistack/Debian_${version_id}/ /" | tee /etc/apt/sources.list.d/alvistack.list >/dev/null
    apt update -y || { echo "添加 APT 仓库失败"; exit 1; }
}

# 安装 Podman
install_podman() {
    apt -y install podman uidmap dbus-x11 slirp4netns libpam-systemd podman-aardvark-dns podman-netavark || { echo "安装 Podman 失败"; exit 1; }
}

update_podman_network() {
	podman network update podman
	sed -i 's/"dns_enabled": false/"dns_enabled": true/' /etc/containers/networks/podman.json
	podman network update podman
}



# 执行脚本流程
main() {
    check_root       # 检查 root 权限
    install_packages   # 安装必要软件包
    add_gpg_key        # 添加 GPG 密钥
    add_apt_repo       # 添加 APT 仓库并更新
    install_podman     # 安装 Podman
    update_podman_network
    pip3 install https://github.com/containers/podman-compose/archive/devel.tar.gz
    echo "podman和podman-compose安装完成,请退出终端重新连接"
}

# 执行主函数
main
