#!/bin/sh
#
# Copyright 2009 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# This script is part of the coccoc-browser package.
#
# It creates the repository configuration file for package updates, and it
# monitors that config to see if it has been disabled by the overly aggressive
# distro upgrade process (e.g.  intrepid -> jaunty). When this situation is
# detected, the respository will be re-enabled. If the respository is disabled
# for any other reason, this won't re-enable it.
#
# This functionality can be controlled by creating the $DEFAULTS_FILE and
# setting "repo_reenable_on_distupgrade" to "true" or "false" as desired.
# An empty $DEFAULTS_FILE is the same as setting it to "false".
#
# The $DEFAULTS_FILE also has a setting "repo_add_once" which can be set
# to "false" to prevent the package install from adding the repo altogether.

# System-wide package configuration.
DEFAULTS_FILE="/etc/default/coccoc-browser"

# sources.list setting for coccoc-browser updates.
REPOCONFIG="deb [arch=any] https://browser-linux.coccoc.com/deb/ stable main"
REPOCONFIGREGEX="deb (\[arch=[^]]*\bany\b[^]]*\][[:space:]]*) https?://browser-linux.coccoc.com/deb/ stable main"
# CocCoc's APT repository key

PGP_KEY_CHECKSUM=""

PGP_KEY_DATA=$(cat <<KEYDATA
mQINBGjjZ1YBEADFZ2tBQsAHx/lSPl32jMoMmqZiCy5qSElIghdlrHxo7Ba3+2A6mlg2WsY2E63G
v0Uy1jhvTPwWImKRDccTwfi9toePiWvluldtpeM7bOquT6XNhsLmcER4LVRTmTuBRtM1spxmuE4i
iqlr77bBrd65xfMb6HVf9wnQ1PITlM7zdmE3YZ5HTB5Pcv8RZQZXgl3T8DRUiBqZdoXEI6PgAzEc
Ldf9tXpYH8aOIc1OZa3+fLVRWp44doY3F7Eocbwu2q6CgX6vNOOsyDt6aX82RPoQTewpMcMDQ+SR
cka+hqTzZMJ+gXqiWuivTYNxu5x44tE4pldfCmUjG9bzR4w0F1SZ6yI9tTAQjWDVfCo8haSMbq68
EDfIJxBC3OCDibLC4vRMddEzF1K6Frnv/oGMTpNWHPQ/a6kxgMSPQ9SjaChnkFp4mcDkG/ZVXw7G
Fuv2kh9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
toZww0A+i2M3bXpN
KEYDATA
)

APT_CONFIG="$(command -v apt-config 2>/dev/null)"

GPG_FILE="/usr/share/keyrings/coccoc-browser.gpg"

# Set variables for the locations of the apt trusted keyrings.
find_apt_trusted() {
  eval $("$APT_CONFIG" shell APT_TRUSTEDDIR 'Dir::Etc::trustedparts/d')
}

# Set variables for the locations of the apt sources lists.
find_apt_sources() {
  eval $("$APT_CONFIG" shell APT_SOURCESDIR 'Dir::Etc::sourceparts/d')
  SOURCES_FILE="$APT_SOURCESDIR/coccoc-browser.sources"
}

# Install the repository/package signing keys. The key cannot be part of the
# package since it's still needed if the package is removed but not purged.
install_key() {
  if [ ! -e /usr/share/keyrings ]; then
    mkdir -p /usr/share/keyrings
    chmod 755 /usr/share/keyrings
  fi

  # Use a temporary file to ensure atomic updates
  echo "$PGP_KEY_DATA" | base64 -d >"$GPG_FILE.$$.tmp"
  chmod 644 "$GPG_FILE.$$.tmp"
  mv "$GPG_FILE.$$.tmp" "$GPG_FILE"
}

uninstall_key() {
  rm -f "$GPG_FILE"
}

remove_legacy_key() {
  find_apt_trusted
  rm -f "$APT_TRUSTEDDIR/coccoc-browser.gpg"
}

remove_legacy_list() {
  find_apt_sources
  LEGACY_LIST="$APT_SOURCESDIR/coccoc-browser.list"
  if [ ! -f "$LEGACY_LIST" ]; then
    return
  fi

  # Check for other sources (strict check for 'ours')
  # If there are any lines starting with 'deb' (commented or not) that do NOT
  # match our strict regex, keep the file.
  if grep -E "^[[:space:]]*#?[[:space:]]*deb" "$LEGACY_LIST" |
    grep -v -E \
    "^[[:space:]]*#?[[:space:]]*$REPOCONFIGREGEX" >/dev/null;
  then
    # Other sources exist, comment out ours (strict match)
    sed -i -E "s|^[[:space:]]*($REPOCONFIGREGEX)|# \1|" "$LEGACY_LIST"
  else
    # No other sources, safe to remove
    rm -f "$LEGACY_LIST"
  fi
}

# Generate the content of the .sources file
gen_sources_content() {
  cat <<EOF
### THIS FILE IS AUTOMATICALLY CONFIGURED ###
# Changes to this file will not be preserved.
# This file will not be recreated if removed.
X-Repolib-Name: Coc Coc Browser
Types: deb
URIs: https://browser-linux.coccoc.com/deb/
Suites: stable
Components: main
Architectures: any
Signed-By: $GPG_FILE
EOF
}

# Add the Google repository to the apt sources. The sources cannot be part of
# the package since it's still needed if the package is removed but not purged.
create_sources_lists() {
  find_apt_sources

  gen_sources_content >"$SOURCES_FILE.$$.tmp"
  chmod 644 "$SOURCES_FILE.$$.tmp"
  mv "$SOURCES_FILE.$$.tmp" "$SOURCES_FILE"

  if [ -r "$DEFAULTS_FILE" ]; then
    if grep -q "^[[:space:]]*repo_add_once=" "$DEFAULTS_FILE"; then
      sed -i -e \
        's/^[[:space:]]*repo_add_once=.*/repo_add_once="false"/' \
        "$DEFAULTS_FILE"
    else
      echo 'repo_add_once="false"' >>"$DEFAULTS_FILE"
    fi
  fi
}

# Remove our custom sources file.
clean_sources_lists() {
  find_apt_sources
  rm -f "$SOURCES_FILE"
}

install_deb822_sources() {
  find_apt_sources
  LEGACY_LIST="$APT_SOURCESDIR/coccoc-browser.list"

  SHOULD_INSTALL_SOURCES=0
  # Detect new installs.
  if [ -r "$DEFAULTS_FILE" ]; then
    if grep -E -q \
      '^[[:space:]]*repo_add_once=[[:space:]]*["'\'']?true["'\'']?' \
      "$DEFAULTS_FILE"; then
      SHOULD_INSTALL_SOURCES=1
    fi
  else
    SHOULD_INSTALL_SOURCES=1
    echo 'repo_add_once="true"' >"$DEFAULTS_FILE"
    echo 'repo_reenable_on_distupgrade="true"' >>"$DEFAULTS_FILE"
  fi

  if [ -f "$SOURCES_FILE" ]; then
    # The new .sources file already exists. Recreate it in case it got disabled
    # during a dist upgrade.
    SHOULD_INSTALL_SOURCES=1
  elif [ -f "$LEGACY_LIST" ]; then
    # Migrate a legacy .list file to the new .sources format.
    if grep -E -q "^[[:space:]]*$REPOCONFIGREGEX" "$LEGACY_LIST"; then
      SHOULD_INSTALL_SOURCES=1
    elif grep -E -q \
      "^[[:space:]]*#[[:space:]]*$REPOCONFIGREGEX[[:space:]]*# disabled on \
upgrade to .*" \
      "$LEGACY_LIST"; then
      SHOULD_INSTALL_SOURCES=1
    fi
  fi

  if [ "$SHOULD_INSTALL_SOURCES" -eq 1 ]; then
    create_sources_lists
  fi
}

## MAIN ##
if [ -r "$DEFAULTS_FILE" ]; then
  . "$DEFAULTS_FILE"
fi

install_key

if [ "$repo_add_once" = "true" ]; then
  create_sources_lists
elif [ "$repo_reenable_on_distupgrade" = "true" ]; then
  install_deb822_sources
fi
