#!/usr/bin/env bash
# Usage: curl -fsSL https://repo.selfhostedemailserver.com/install.sh | bash
set -euo pipefail

REPO_URL="https://repo.selfhostedemailserver.com"
KEYRING="/usr/share/keyrings/selfhost-email.gpg"
LIST="/etc/apt/sources.list.d/selfhost-email.list"
PACKAGE="selfhost-email"

# --- Colors ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

info()    { echo -e "${BLUE}::${NC} $*"; }
success() { echo -e "${GREEN}OK${NC} $*"; }
warn()    { echo -e "${YELLOW}!!${NC} $*"; }
error()   { echo -e "${RED}ERROR${NC} $*" >&2; }
step()    { echo -e "\n${BOLD}[$1/$TOTAL] $2${NC}"; }

confirm() {
    local prompt="$1"
    local reply
    echo -en "${YELLOW}?${NC} ${prompt} [Y/n] "
    read -r reply </dev/tty
    case "$reply" in
        [nN]|[nN][oO]) return 1 ;;
        *) return 0 ;;
    esac
}

TOTAL=4

# --- Header ---
echo ""
echo -e "${BOLD}  selfhost-email installer${NC}"
echo -e "  ${BLUE}${REPO_URL}${NC}"
echo ""

# --- Pre-flight checks ---
if [ "$(id -u)" -ne 0 ]; then
    error "This script must be run as root."
    echo "  Try: curl -fsSL ${REPO_URL}/install.sh | sudo bash"
    exit 1
fi

if ! command -v curl &>/dev/null; then
    error "curl is required but not installed."
    exit 1
fi

if ! command -v gpg &>/dev/null; then
    error "gpg is required but not installed."
    echo "  Install it with: apt install gnupg"
    exit 1
fi

# Detect codename
if [ -f /etc/os-release ]; then
    . /etc/os-release
    CODENAME="${VERSION_CODENAME:-noble}"
    DISTRO="${NAME:-Linux}"
else
    CODENAME="noble"
    DISTRO="Linux"
fi

info "Detected: ${BOLD}${DISTRO}${NC} (${CODENAME})"
echo ""

echo "This script will:"
echo "  1. Import the selfhost-email GPG signing key"
echo "  2. Add the APT repository"
echo "  3. Update package lists"
echo "  4. Install the ${PACKAGE} package"
echo ""

if ! confirm "Continue with installation?"; then
    echo "Aborted."
    exit 0
fi

# --- Step 1: Import GPG key ---
step 1 "Importing GPG signing key"

if [ -f "$KEYRING" ]; then
    warn "Keyring already exists at ${KEYRING}"
    if ! confirm "Overwrite existing keyring?"; then
        success "Keeping existing keyring"
    else
        curl -fsSL "${REPO_URL}/pubkey.gpg" | gpg --dearmor -o "$KEYRING"
        success "Signing key imported to ${KEYRING}"
    fi
else
    curl -fsSL "${REPO_URL}/pubkey.gpg" | gpg --dearmor -o "$KEYRING"
    success "Signing key imported to ${KEYRING}"
fi

# --- Step 2: Add repository ---
step 2 "Adding APT repository"

REPO_LINE="deb [signed-by=${KEYRING}] ${REPO_URL} ${CODENAME} main"

if [ -f "$LIST" ]; then
    warn "Source list already exists at ${LIST}"
    if ! confirm "Overwrite existing source list?"; then
        success "Keeping existing source list"
    else
        echo "$REPO_LINE" > "$LIST"
        success "Repository added"
    fi
else
    echo "$REPO_LINE" > "$LIST"
    success "Repository added"
fi

info "Source: ${REPO_LINE}"

# --- Step 3: Update package lists ---
step 3 "Updating package lists"

apt-get update -qq
success "Package lists updated"

# --- Step 4: Install package ---
step 4 "Installing ${PACKAGE}"

# Check if already installed
if dpkg -l "$PACKAGE" 2>/dev/null | grep -q "^ii"; then
    INSTALLED_VER=$(dpkg -l "$PACKAGE" | grep "^ii" | awk '{print $3}')
    warn "${PACKAGE} is already installed (version ${INSTALLED_VER})"
    AVAILABLE_VER=$(apt-cache policy "$PACKAGE" | grep "Candidate:" | awk '{print $2}')
    if [ "$INSTALLED_VER" = "$AVAILABLE_VER" ]; then
        success "Already at latest version"
    else
        info "Available version: ${AVAILABLE_VER}"
        if confirm "Upgrade to ${AVAILABLE_VER}?"; then
            apt-get install -y "$PACKAGE"
            success "${PACKAGE} upgraded to ${AVAILABLE_VER}"
        else
            success "Keeping current version"
        fi
    fi
else
    AVAILABLE_VER=$(apt-cache policy "$PACKAGE" | grep "Candidate:" | awk '{print $2}')
    info "Version: ${AVAILABLE_VER}"
    if confirm "Install ${PACKAGE}?"; then
        apt-get install -y "$PACKAGE"
        success "${PACKAGE} installed"
    else
        echo ""
        info "Skipped. You can install later with:"
        echo "  apt install ${PACKAGE}"
    fi
fi

# --- Done ---
echo ""
echo -e "${GREEN}${BOLD}  Installation complete!${NC}"
echo ""
info "The service is running on port 8080"
info "Open your browser to http://$(hostname -I 2>/dev/null | awk '{print $1}' || echo 'your-server-ip'):8080"
echo ""
