#!/bin/bash
set -euo pipefail

export GNUPGHOME=/srv/apt-mirror/debmirror/mirrorkeyring

# ---- What to mirror ----
arch="amd64"  # change to: "amd64,i386" if you need 32-bit too
section="main,restricted,universe,multiverse"
release="noble,noble-updates,noble-security,noble-backports"

# ---- Where to mirror from ----
# For best speed, use a geographically close mirror (and rsync if available).
#server="archive.ubuntu.com"
#server="mirror.uepg.br"
server="ubuntu.c3sl.ufpr.br"

# Choose transfer method: http | https | rsync
method="rsync"

# Remote archive root differs slightly by method:
# - http/https typically uses "/ubuntu"
# - rsync typically uses "ubuntu" (no leading slash) per debmirror defaults
inPath_http="/ubuntu"
inPath_rsync="ubuntu"

# ---- Where to store locally ----
outPath="/srv/apt-mirror/debmirror/ubuntu"

# ---- Tuning ----
include_sources=0          # 1 = include source packages, 0 = no sources
state_cache_days=30        # speeds up repeat runs by caching mirror state :contentReference[oaicite:3]{index=3}
timeout_seconds=900        # network timeout for rsync/ftp (and generally safe to raise) :contentReference[oaicite:4]{index=4}

# Cleanup mode:
#   --postcleanup is the default and keeps the mirror consistent :contentReference[oaicite:5]{index=5}
cleanup_mode="--postcleanup"
# cleanup_mode="--nocleanup"   # use temporarily during migration/testing :contentReference[oaicite:6]{index=6}

# ---- Derived flags ----
if [[ "$include_sources" -eq 1 ]]; then
  source_flag="--source"
else
  source_flag="--nosource"
fi

extra_args=(
  "--method=${method}"
  "--progress"
  "--timeout=${timeout_seconds}"
  "--state-cache-days=${state_cache_days}"
  "${cleanup_mode}"
)

if [[ "$method" == "rsync" ]]; then
  inPath="${inPath_rsync}"
  # For rsync, debmirror notes --diff=none may be most efficient. :contentReference[oaicite:7]{index=7}
  extra_args+=(
    "--diff=none"
    "--retry-rsync-packages=10"   # experimental but useful for flaky rsync connections :contentReference[oaicite:8]{index=8}
    "--rsync-batch=2000"          # reduce rsync command overhead on huge runs :contentReference[oaicite:9]{index=9}
  )
else
  inPath="${inPath_http}"
  # Default is --diff=use; keeping it explicit is fine for http/https. :contentReference[oaicite:10]{index=10}
  extra_args+=("--diff=use")
fi

# ---- Run ----
debmirror \
  -a "$arch" \
  -s "$section" \
  -d "$release" \
  -h "$server" \
  -r "$inPath" \
  "$source_flag" \
  "${extra_args[@]}" \
  "$outPath"

