#!/bin/bash

# This shell script is used to complete the manual steps at the end of the
# release process.

set -euo pipefail

readonly usage="Usage: $0 {{ source version x.y.z }}"

if [[ "$#" -lt 1 ]]; then
  echo "${usage}" >&2
  exit 1
fi

readonly source_version=$1

shift 1;

# The only thing this script still does is the apt push
push_apt=1

if ! tty -s; then
  echo 'ERROR: tty was NOT detected. This script may need various login credentials to be entered interactively.'  >&2
  exit 2;
fi

if [[ "${push_apt}" -ne 0 ]] && ! command -v aptly &>/dev/null; then
  echo 'ERROR: aptly(1) was NOT found. Fix with apt-get install aptly or brew install aptly.' >&2
  exit 3
fi

if [[ "${push_apt}" -ne 0 ]] && ! command -v aws &>/dev/null; then
  echo 'ERROR: aws(1) was NOT found. Fix with apt-get install awscli or brew install awscli.' >&2
  exit 4
fi

# curl is always available on macOS.
if ! command -v curl &>/dev/null; then
  echo 'ERROR: curl(1) was NOT found. Fix with apt-get install curl.' >&2
  exit 5
fi

if [[ "${push_apt}" -ne 0 ]] && ! command -v gpg &>/dev/null; then
  echo 'ERROR: gpg(1) was NOT found. Fix with apt-get install gnupg or brew install gnupg.' >&2
  exit 6
fi

# Sanity check that the release for the source version exists and has been
# published.
if ! curl --fail --head --location --output /dev/null \
    "https://api.github.com/repos/RobotLocomotion/drake/releases/tags/v${source_version}"; then
  echo "ERROR: GitHub release v${source_version} does NOT exist." >&2
  exit 8
fi

# TODO(jwnimmer-tri) We need "noble" here also, once we support it.
platforms=( jammy )

readonly gpg_key="$(
  curl --fail https://drake-apt.csail.mit.edu/drake.asc | \
  gpg --with-colons --show-keys --fingerprint | \
  grep -m1 -E '^fpr:' | cut -c 4- | tr -d :)"

if ! [[ "${gpg_key}" =~ ^[a-fA-F0-9]{40}$ ]]; then
  echo "Error: gpg_key value expected to be a length 40 hexadecimal string." >&2
  exit 1
fi

if [[ "${push_apt}" -ne 0 ]] && ! gpg --list-secret-keys "${gpg_key}" &>/dev/null; then
  echo "ERROR: GPG secret key ${gpg_key} does NOT exist." >&2
  exit 10
fi

if [[ "${push_apt}" -ne 0 ]]; then
  if [ ! -s "${HOME}/.aptly.conf" ]; then
    echo "ERROR: aptly is NOT configured." >&2
    exit 11
  fi
fi

readonly temp_dir="$(mktemp -u)"

mkdir -p "${temp_dir}"
pushd "${temp_dir}"

if [[ "${push_apt}" -ne 0 ]]; then
  set -x

  # Download the current version of the aptly database from S3.
  aws s3 sync --delete s3://drake-infrastructure/aptly/.aptly "${HOME}/.aptly"

  # Run this command to add a new repository
  # aptly repo create -distribution=<platform> drake-<platform>

  # Run this command to add or replace a package
  # aptly repo add [-force-replace] drake-<platform> <package file>

  for platform in "${platforms[@]}"; do
    mkdir -p "${platform}"
    pushd "${platform}"

    filename="drake-dev_${source_version}-1_amd64.deb"

    curl --fail --location --remote-name \
      "https://drake-packages.csail.mit.edu/drake/release/${platform}/${filename}"

    # Add the Debian package to the aptly database.
    aptly repo add "drake-${platform}" "${filename}"
    aptly snapshot create "drake-${platform}-${source_version}" \
      from repo "drake-${platform}"

    # Publish the new apt repository to S3.
    aptly publish switch -gpg-key="${gpg_key: -8}" "${platform}" \
      "s3:drake-apt.csail.mit.edu/${platform}:" "drake-${platform}-${source_version}"

    # The first time a repository is published use snapshot not switch
    # aptly publish snapshot -gpg-key="${gpg_key: -8}" -distribution="${platform}" \
    #  "drake-${platform}-${source_version}" "s3:drake-apt.csail.mit.edu/${platform}:"

    # Invalidate the cached apt repository.
    aws cloudfront create-invalidation --distribution-id E2RAGJYS5GNIOS \
      --paths "/${platform}/dists/${platform}/*"

    popd
  done

  # Upload the new version of the aptly database to S3.
  aws s3 sync --delete --exclude .DS_Store "${HOME}/.aptly" \
    s3://drake-infrastructure/aptly/.aptly

  set +x
fi

popd

# Remove the downloaded files on success.
rm -rf "${temp_dir}"
