#!/usr/bin/bash
# -*- mode: Shell-script; sh_shell: "bash"; -*-

set -euo pipefail
IFS=$'\n\t'
LANG=C

SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
source /etc/os-release

# ----------------------------------------------------------------------
#  Preconditions
# ----------------------------------------------------------------------
if [ "$EUID" -ne 0 ]; then
    echo "Please run as root"
    exit 1
fi

# ----------------------------------------------------------------------
#  Constants
# ----------------------------------------------------------------------
KEYRING_DIR="/usr/share/keyrings"
KEYFILE_NAME="home_kimi.gpg"
KEYFILE="${KEYRING_DIR}/${KEYFILE_NAME}"
REPO_URL="http://download.opensuse.org/repositories/home:/kimi:/utils/xUbuntu_${VERSION_ID}"
KEY_URL="${REPO_URL}/Release.key"
SRC_GLOB="/etc/apt/sources.list.d/home:kimi:*.list"
ENABLE_BACKUP=0

# ----------------------------------------------------------------------
#  Helper functions
# ----------------------------------------------------------------------
die() {
    printf 'Error: %s\n' "$*" >&2
    exit 1
}

backup_file() {
    local f=$1 s=$2
    [[ -f "$f" ]] && cp -a -- "$f" "${f}${s}" && echo "Backup: ${f}${s}"
}

set_key_permissions() {
    chmod 0644 "$KEYFILE"
    chown root:root "$KEYFILE"
    echo "Permissions set on $KEYFILE"
}

# ----------------------------------------------------------------------
#  Rename expired key only when *any* backup exists
# ----------------------------------------------------------------------
rename_expired_key() {
    local file=$1 base="${file%~}" backup_glob="${base}*~"
    # if no backup matching the pattern exists, do nothing
    if ! compgen -G "$backup_glob" >/dev/null; then
        return
    fi
    local ts=$(date '+.%Y-%m-%d_%H-%M-%S')
    local new="${base}${ts}~"
    echo "Renaming expired $file → $new"
    mv -v -- "$file" "$new"
}

# ----------------------------------------------------------------------
#  0 – Clean up existing keys
# ----------------------------------------------------------------------
mkdir -p "$KEYRING_DIR"

# collect all possible key locations
shopt -s nullglob
found=()
for d in /etc/apt/trusted.gpg.d /etc/apt/keyrings /usr/share/keyrings; do
    found+=("$d"/home_kimi*)
done
shopt -u nullglob

# delete empty files
for f in "${found[@]}"; do
    [[ -f "$f" && ! -s "$f" ]] && echo "Removing empty $f" && rm -f "$f"
done

# refresh list after deletions
found=()
shopt -s nullglob
for d in /etc/apt/trusted.gpg.d /etc/apt/keyrings /usr/share/keyrings; do
    found+=("$d"/home_kimi*)
done
shopt -u nullglob

if ((${#found[@]})); then
    echo "Found ${#found[@]} home_kimi key(s):"
    printf '  %s\n' "${found[@]}"

    # ---- rename expired keys ----
    for f in "${found[@]}"; do
        if gpg --show-key --with-colons "$f" 2>/dev/null |
            awk -F: '$1=="pub"{print $7}' |
            while read -r exp; do
                [[ -z "$exp" ]] && echo "no-expiry" && exit 0
                ((exp < $(date +%s))) && echo "expired" && exit 0
            done | grep -qE 'expired|no-expiry'; then
            rename_expired_key "$f"
        fi
    done

    # ---- move non‑canonical keys ----
    for f in "${found[@]}"; do
        [[ -e "$f" ]] || continue
        src=$(readlink -f "$f")
        dest=$(readlink -f "$KEYRING_DIR/${f##*/}")

        if [[ "$src" == "$dest" ]]; then
            echo "Already in $KEYRING_DIR: $f"
            continue
        fi
        echo "Moving $f → $KEYRING_DIR/"
        mv -v -- "$f" "$KEYRING_DIR/"
    done
else
    echo "No existing home_kimi keys found."
fi

# ----------------------------------------------------------------------
#  1 – Keep only the newest key (by expiry)
# ----------------------------------------------------------------------
shopt -s nullglob
keys=("$KEYRING_DIR"/home_kimi*.gpg)
shopt -u nullglob

if ((${#keys[@]} > 1)); then
    newest=""
    newest_exp=0

    get_expiry() {
        gpg --show-key --with-colons "$1" 2>/dev/null |
            awk -F: '$1=="pub"{print $7}' | head -n1
    }

    for k in "${keys[@]}"; do
        exp=$(get_expiry "$k")
        exp=${exp:-0}
        ((exp == 0)) && exp=$(stat -c %Y "$k" 2>/dev/null || stat -f %m "$k")
        ((exp > newest_exp)) && newest_exp=$exp && newest=$k
    done

    echo "Keeping newest key: $newest"
    [[ -f "$KEYFILE" ]] && mv -v "$KEYFILE" "${KEYFILE}.$(date '+%Y-%m-%d_%H-%M-%S')~"
    mv -v "$newest" "$KEYFILE"
    for k in "${keys[@]}"; do
        [[ "$k" != "$KEYFILE" ]] && rm -f "$k"
    done
fi

# ----------------------------------------------------------------------
#  2 – Download/refresh the key
# ----------------------------------------------------------------------
need_download=1
if [[ -f "$KEYFILE" ]] && /usr/local/bin/check-apt-key-if-less-than-x-days-to-expiry "$KEYFILE"; then
    need_download=0
    echo "Existing key still valid."
fi

if ((need_download)); then
    echo "Downloading key from $KEY_URL"
    wget -qO- "$KEY_URL" | gpg --dearmor >"$KEYFILE".new ||
        die "Failed to download/dearmor key"
    mv -f "$KEYFILE".new "$KEYFILE"
    set_key_permissions
else
    set_key_permissions
fi

# ----------------------------------------------------------------------
# 3 – Ensure every home:kimi list file contains the signed‑by clause
# ----------------------------------------------------------------------
shopt -s nullglob
src_files=($SRC_GLOB)
shopt -u nullglob

if ((${#src_files[@]} == 0)); then
    echo "No home:kimi source‑list files found."
    exit 0
fi

for f in "${src_files[@]}"; do
    ((ENABLE_BACKUP)) && cp -a -- "$f" "${f}.orig" && echo "Backup: ${f}.orig"

    # If the file already contains the correct signed‑by, skip it
    if grep -q "signed-by=${KEYFILE}" "$f"; then
        echo "signed‑by already present in $f"
        continue
    fi

    # Build a new version of the file line‑by‑line
    {
        while IFS= read -r line; do
            if [[ $line =~ ^[[:space:]]*deb[[:space:]]+ ]]; then
                if [[ $line =~ ^([[:space:]]*deb[[:space:]]+)(\[[^]]*\])?[[:space:]]*([^[:space:]]+)([[:space:]].*)$ ]]; then
                    prefix="${BASH_REMATCH[1]}"
                    opts="${BASH_REMATCH[2]}"
                    url="${BASH_REMATCH[3]}"
                    rest="${BASH_REMATCH[4]}"

                    # Match any home:/kimi repo (handles utils, linphone-desktop, test000, etc.)
                    if [[ "$url" =~ ^https?://download\.opensuse\.org/repositories/home:/kimi: ]]; then
                        if [[ -n $opts ]]; then
                            new_opts="${opts%]}"
                            new_opts="${new_opts} signed-by=${KEYFILE}]"
                        else
                            new_opts="[signed-by=${KEYFILE}]"
                        fi
                        echo "${prefix}${new_opts} ${url}${rest}"
                        continue
                    fi
                fi
            fi
            echo "$line"
        done <"$f"
    } >"${f}.tmp" && mv -f "${f}.tmp" "$f"

    echo "Updated signed‑by in $f"
done

# ----------------------------------------------------------------------
#  4 – Clean APT cache
# ----------------------------------------------------------------------
echo "Cleaning APT cache ..."
apt clean
rm -rf /var/lib/apt/lists/*

# ----------------------------------------------------------------------
#  5 – Show final state (useful for debugging)
# ----------------------------------------------------------------------
echo
echo "Key file:"
ls -al "$KEYFILE"
echo

echo "Updated source‑list files:"
# <-- use the correct variable name here
for f in "${src_files[@]}"; do
    echo "---- $f ----"
    grep -E '^deb' "$f" || echo "(no deb line found)"
done
echo
echo "Done."
