#!/usr/bin/env bash
# --------------------------------------------------------------------------------
PROJECT=3rdp4r7yr3p0
DISTRIBUTION=$1; shift 1
SCRIPT=$(basename $0)
# --------------------------------------------------------------------------------
function _m { t="$1"; shift 1; echo -e " $t) $*"; }
function _e { _m "ERROR!" "$*\n   ..> [ENTER] to exit."; read; exit; }
function _w { _m "warning!" "$*\n   ..> [ENTER] to proceed, [CTRL+C] to quit."; read; }
# --------------------------------------------------------------------------------
_m ${SCRIPT} "https://build.opensuse.org/project/show/home:${PROJECT}"

[ $UID -ne 0 ] &&
  _e "please run as ROOT"

[ $# -eq 0 ] &&
  _e "usage: ${SCRIPT} DISTRIBUTION REPO1 REPO2..." 
# --------------------------------------------------------------------------------
unset repo; declare -A repo
unset prio; declare -A prio
unset dist; declare -A dist

repo[applications]="4pp5c0nfm15c"; prio[applications]=905
repo[audio]="4udfr4m3wl1b"; prio[audio]=904
repo[desktop]="d35k4pp57h3m"; prio[desktop]=903
repo[libraries]="l1b5hw3d3v3l"; prio[libraries]=902
repo[experimental]="3xpd3vl1b4pp"; prio[experimental]=901
repo[core]="c0r3f1rmwk3r"; prio[core]=900
repo[transient]="7r47mp4ppl1b"; prio[transient]=91
repo[support]="bldd3v3l5upp"; prio[support]=90

dist[bookworm]="Debian_12"
dist[trixie]="Debian_13"
dist[forky]="Debian_14"
dist[unstable]="Debian_Unstable"
dist[noble]="xUbuntu_24.04"
dist[resolute]="xUbuntu_26.04"
# --------------------------------------------------------------------------------
[ ${#dist[${DISTRIBUTION}]} -eq 0 ] &&
  _e "distribution unavailable: ${DISTRIBUTION}"
# --------------------------------------------------------------------------------
for r in $@; do
  if [ ${#repo[${r}]} -gt 0 ]; then
    id=${repo[${r}]}
    obs=${dist[${DISTRIBUTION}]}
    desc="OBS home:${PROJECT} (${r}) [${id}]"
    u_key=https://download.opensuse.org/repositories/home:${PROJECT}:${id}/${obs}/Release.key
    key=/etc/apt/trusted.gpg.d/home_${PROJECT}_${id}.gpg
    list=/etc/apt/sources.list.d/home:${PROJECT}:${id}.list
    pref=/etc/apt/preferences.d/home:${PROJECT}:${id}.pref
    curl -fsSL ${u_key} >& /dev/null
    if [ $? -eq 0 ]; then
      rm -f ${list} ${pref}
      _m "repo added" ${desc}
      curl -fsSL ${u_key} | gpg --dearmor | tee ${key} >& /dev/null
      cat <<EOF > ${list}
# ${desc}
deb http://download.opensuse.org/repositories/home:/${PROJECT}:/${id}/${obs}/ /
# deb-src http://download.opensuse.org/repositories/home:/${PROJECT}:/${id}/${obs}/ /
EOF
      cat <<EOF >> ${pref}
# ${desc}
Package: *
Pin: release l=home:${PROJECT}:${id}
Pin-Priority: ${prio[${r}]} 
EOF
    else
      _e "unable to retrieve key: ${u_key}"
    fi
  else
    _w "repo unavailable: ${r}"
  fi
done
_m ${SCRIPT} "all DONE."
# --------------------------------------------------------------------------------
