#!/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 prisma-access-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/prisma-access-browser"

# sources.list setting for prisma-access-browser updates.
REPOCONFIG="deb [arch=amd64] https://updates.talon-sec.com/linux/prisma-access-browser/deb/ stable main"
REPOCONFIGREGEX="deb (\[arch=[^]]*\bamd64\b[^]]*\][[:space:]]*) https?://updates.talon-sec.com/linux/prisma-access-browser/deb/ stable main"
# This file is automatically generated by update_key_include.py
# Do not edit this file directly.

# This is used as a priority value for the key file, so newer
# keyrings should always take priority.
PGP_KEY_VERSION=2

# pub   rsa4096 2016-04-12 [SC]
#       EB4C1BFD4F042F6DDDCCEC917721F63BD38B4796
# uid           [ unknown] Google Inc. (Linux Packages Signing Authority) <linux-packages-keymaster@google.com>
# sub   rsa4096 2024-01-30 [S] [expires: 2027-01-29]
# sub   rsa4096 2025-01-07 [S] [expires: 2028-01-07]
PGP_KEY_DATA=$(cat <<KEYDATA
mQINBGfRTr0BEADEbUFbs/UbllfrWQBHthcZdH5sXSXoeNGhkrzSsa3F1mqk7MVs
+u3gT7HCVaPG58qyXAngYgY9mrnUasOm4WuQ8q8WHlgA/mRneh/wCfrtXmC97YTB
KhjN3ldhwUPpCZ9YQ2xlUGj6hrhRT7VR+R6mvfoxayfjtok7YeQ49ImPVEOeVoGn
74adNgA/HuPTan5H5uB+YguBh4Zlmz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wr4UJ1Eqpx3Scimx6N7me9R5ZfuIYe7WUCu8ZEVy9xaS5RNCF6FWpzuatXM8f4
GIQGFoCNLzJ5mIKd0oqTU1+TsMLhyna2RkZY6MEcpl925xmYgO73TYHSaP843QSa
f6rdS7NAp5PvPlS+OmVqAZ7e+y/s8Yb0CSOnIb9Y0nYhsbkPVWLLhabnrzC/2Xdw
PPpF/CJhxv9MIg6E8vh+/kmBXS8Z349TbPOpW3y/jpGBqcjFDIJav689BUCCVS0H
fYEqaB3hcdsOZHQwMeCoNb7dfErZyKwUCxjlNtTtuUwGlfWX2LLqrEbzOh+hMfot
ecUZ4K9DYJ5D8A==
KEYDATA
)

PGP_KEY_CHECKSUM="=+H/O"

# TALON: Python script used to calculate checksum in case we ever rotate our key
# import struct
#
# # Read the key data from the file
# with open('src/chrome/installer/linux/common/key.include', 'r') as f:
#     content = f.read()
#
# # Extract the base64 key data between the KEYDATA markers
# import re
# match = re.search(r'cat <<KEYDATA\n(.*?)\nKEYDATA', content, re.DOTALL)
# key_b64 = match.group(1).strip()
#
# # Decode the base64 data
# import base64
# key_bytes = base64.b64decode(key_b64)
#
# # Calculate CRC-24 per RFC 4880 Section 6.1
# CRC24_INIT = 0xB704CE
# CRC24_POLY = 0x1864CFB
#
# crc = CRC24_INIT
# for byte in key_bytes:
#     crc ^= byte << 16
#     for i in range(8):
#         crc <<= 1
#         if crc & 0x1000000:
#             crc ^= CRC24_POLY
#     crc &= 0xFFFFFF
#
# # Encode as base64
# crc_bytes = struct.pack('>I', crc)[1:]  # 3 bytes, big-endian
# checksum = '=' + base64.b64encode(crc_bytes).decode()
# print(f'Current checksum: =AcRC')
# print(f'Correct checksum: {checksum}')

# TALON: command to verify checksum (will print something like gpg: CRC error; F87FCE - F87FDA if the checksum is incorrect):
# TALON: gpg can be installed with `brew install gpg` on macos
#  source key.include && \
#  echo -e "-----BEGIN PGP PUBLIC KEY BLOCK-----\n\n${PGP_KEY_DATA}\n${PGP_KEY_CHECKSUM}\n-----END PGP PUBLIC KEY BLOCK-----" | gpg --import --dry-run -

PGP_SUBKEYS="32EE5355A6BC6E42 FD533C07C264648F"

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

GPG_FILE="/usr/share/keyrings/prisma-access-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/prisma-access-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/prisma-access-browser.gpg"
}

remove_legacy_list() {
  find_apt_sources
  LEGACY_LIST="$APT_SOURCESDIR/prisma-access-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: Prisma Access Browser
Types: deb
URIs: https://updates.talon-sec.com/linux/prisma-access-browser/deb/
Suites: stable
Components: main
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/prisma-access-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
