#!/bin/bash

# Chromium-Gost for Porteus
# Version: 2026-09-25
#
# Copyright 2023-2030, Blaze, Dankov, Russia
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

export LC_ALL=C
export XZ_OPT="-T0"
set -euo pipefail

PRGNAM=${PRGNAM:-chromium-gost}
OUTPUT=${OUTPUT:-/tmp}
TMPDIR=/tmp/portch
PKG="$TMPDIR/package-$PRGNAM"
PKGINFO="$PKG/var/lib/pkgtools/packages"
ARCH=$(uname -m)

BOLD=$'\033[1m'
CYAN=$'\033[96m'
GREEN=$'\033[92m'
YELLOW=$'\033[93m'
RED=$'\033[91m'
RESET=$'\033[0m'

cleanup() { rm -rf "$TMPDIR" 2>/dev/null || true; }
trap cleanup EXIT INT TERM HUP

if [ "$(id -u)" -ne 0 ]; then
  printf "\n${RED}Root required.${RESET}\n"
  exit 1
fi

printf "\nFetching latest release info...\n"
VERSION=$(
  wget --spider -S "https://github.com/deemru/chromium-gost/releases/latest" 2>&1 |
  grep -i 'location:' |
  grep -oE '[0-9]+(\.[0-9]+)+' |
  tail -n 1 || true
)

if [ -z "$VERSION" ]; then
  printf "${RED}Failed to determine version.${RESET}\n"
  exit 1
fi

SOURCE="https://github.com/deemru/Chromium-Gost/releases/download/${VERSION}/${PRGNAM}-${VERSION}-linux-amd64.rpm"
RPM_FILE="${PRGNAM}-${VERSION}-linux-amd64.rpm"

MYVER=""
if [ -x "/usr/bin/chromium-gost-stable" ]; then
  MYVER=$(/usr/bin/chromium-gost-stable --product-version 2>/dev/null || true)
  printf "[${GREEN}OK${RESET}] Installed version: ${YELLOW}%s${RESET}\n" "${MYVER:-Unknown}"
  if [ "$MYVER" = "$VERSION" ]; then
    printf "Already latest: ${GREEN}%s${RESET}\n" "$VERSION"
    exit 0
  fi
else
  printf "[${CYAN}INFO${RESET}] Chromium-Gost is not installed.\n"
fi

printf "Current: ${YELLOW}%s${RESET} | Available: ${GREEN}%s${RESET}\n" "${MYVER:-None}" "$VERSION"
printf "Build ${PRGNAM} ${GREEN}${VERSION}${RESET} xzm module? [y/N]: "
IFS= read -r -n 1 -s reply || true
printf "\n"

if [[ ! ${reply:-} =~ ^[Yy]$ ]]; then
  printf "Cancelled.\n"
  exit 0
fi

rm -rf "$TMPDIR"
mkdir -p "$PKG" "$OUTPUT"
cd "$PKG" || exit 1

printf "\nDownloading ${CYAN}${BOLD}%s${RESET}\n" "$RPM_FILE"
if ! wget -q --show-progress "$SOURCE" -O "$RPM_FILE"; then
  printf "${RED}Download failed.${RESET}\n"
  exit 1
fi

printf "\nExtracting RPM...\n"
if ! rpm2cpio "$RPM_FILE" | cpio -idm >/dev/null 2>&1; then
  printf "${RED}Extraction failed.${RESET}\n"
  exit 1
fi

rm -f "$RPM_FILE"
rm -rf "$PKG/usr/share/man" "$PKG/etc"

printf "Organizing icons...\n"
SRC="$PKG/opt/chromium-gost"
DST="$PKG/usr/share/icons/hicolor"
mkdir -p "$DST"/{24x24,32x32,48x48,64x64,128x128,256x256}/apps
rm -f "$SRC"/product_logo_{16,32}.png "$SRC/product_logo_32.xpm"

if [ -f "$SRC/product_logo_24.png" ]; then
  mv -f "$SRC/product_logo_24.png" "$DST/24x24/apps/chromium-gost.png"
fi

if [ -f "$SRC/product_logo_48.png" ]; then
  cp -a "$SRC/product_logo_48.png" "$DST/32x32/apps/chromium-gost.png"
  mv -f "$SRC/product_logo_48.png" "$DST/48x48/apps/chromium-gost.png"
fi

for size in 64 128 256; do
  if [ -f "$SRC/product_logo_${size}.png" ]; then
    mv -f "$SRC/product_logo_${size}.png" "$DST/${size}x${size}/apps/chromium-gost.png"
  fi
done

rm -f "$SRC"/product_logo_*.png "$SRC"/product_logo_*.xpm

select_locale() {
  local locales=(af am ar bg bn ca cs da de el en-GB en-US es-419 es et fa fi fil fr gu he hi hr hu id it ja kn ko lt lv ml mr ms nb nl pl pt-BR pt-PT ro ru sk sl sr sv sw ta te th tr uk ur vi zh-CN zh-TW)
  local count=${#locales[@]}
  local max_len=0
  local loc
  local num_width field_width sep_width=2 term_width cols rows
  local i j idx choice

  for loc in "${locales[@]}"; do
    if (( ${#loc} > max_len )); then
      max_len=${#loc}
    fi
  done

  num_width=${#count}
  field_width=$((num_width + 2 + max_len))

  term_width=$(tput cols 2>/dev/null || true)
  if [[ ! $term_width =~ ^[0-9]+$ ]]; then
    term_width=${COLUMNS:-80}
  fi
  if [[ ! $term_width =~ ^[0-9]+$ ]]; then
    term_width=80
  fi
  if (( term_width < 30 )); then
    term_width=30
  fi

  cols=$(( (term_width - 2 + sep_width) / (field_width + sep_width) ))
  if (( cols < 1 )); then cols=1; fi
  if (( cols > 5 )); then cols=5; fi
  if (( cols > count )); then cols=count; fi
  rows=$(( (count + cols - 1) / cols ))

  printf "\n${CYAN}Locale setup${RESET} (%s available):\n" "$count"
  for ((i = 0; i < rows; i++)); do
    printf "  "
    for ((j = 0; j < cols; j++)); do
      idx=$((i + j * rows))
      if (( idx < count )); then
        printf "%${num_width}d) %-${max_len}s" "$((idx + 1))" "${locales[idx]}"
      else
        printf "%${field_width}s" ""
      fi
      if (( j + 1 < cols )); then
        printf "%${sep_width}s" ""
      fi
    done
    printf "\n"
  done

  while true; do
    printf "\nKeep locale [1-%s, 0/Enter=en-US only]: " "$count"
    IFS= read -r choice || choice=""
    choice=${choice//[[:space:]]/}
    if [ -z "$choice" ] || [ "$choice" = "0" ]; then
      choice=0
      break
    fi
    if [[ $choice =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= count )); then
      break
    fi
    printf "${RED}Invalid input.${RESET}\n"
  done

  if (( choice > 0 )); then
    CHOICE=${locales[choice - 1]}
  else
    CHOICE=en-US
  fi

  printf "Selected: ${GREEN}%s${RESET}\n" "$CHOICE"
}

select_locale

printf "\n${CYAN}Cleaning files...${RESET}\n"
if [ -d "$SRC/locales" ]; then
  printf "  Removing locales except en-US and %s...\n" "$CHOICE"
  find "$SRC/locales" -type f ! -name 'en-US.pak' ! -name "${CHOICE}.pak" -delete
fi

if [ -d "$PKG/usr/share/applications" ]; then
  printf "  Cleaning desktop entries...\n"
  rm -f "$PKG/usr/share/applications/org.chromium.Chromium.desktop"
  find "$PKG/usr/share/applications" -maxdepth 1 -type f -name '*.desktop' -exec sed -i '/^MimeType=/d' {} +
fi

printf "  Writing package metadata...\n"
mkdir -p "$PKGINFO"
{
  printf "PACKAGE NAME: %s-%s-%s\n" "$PRGNAM" "$VERSION" "$ARCH"
  printf "PACKAGE DESCRIPTION:\n"
  printf "chromium-gost: Chromium-Gost browser with GOST cryptographic support.\n"
  printf "chromium-gost: Un-googled build.\n"
  printf "chromium-gost: https://github.com/deemru/Chromium-Gost\n"
  printf "FILE LIST:\n"
  find . -mindepth 1 ! -name 'var' ! -path './var/*' -printf '%P\n' | sort
} > "$PKGINFO/${PRGNAM}-${VERSION}-${ARCH}"

printf "\n${CYAN}Building XZM module...${RESET}\n"
MODULE="$OUTPUT/${PRGNAM}-${VERSION}-${ARCH}-${CHOICE}.xzm"
if ! dir2xzm "$PKG" "$MODULE"; then
  printf "\n${RED}[FAIL] Module build failed.${RESET}\n"
  exit 1
fi

if [ -f "$MODULE" ]; then
  SIZE=$(du -h "$MODULE" | cut -f1)
  printf "\n${GREEN}[OK] Module created:${RESET} ${BOLD}%s${RESET}\n" "$MODULE"
  printf "${BOLD}Size:${RESET} ${CYAN}%s${RESET}\n" "$SIZE"
  printf "${BOLD}Copy it to /porteus/modules to survive reboot.${RESET}\n\n"
else
  printf "\n${RED}[FAIL] Module was not created.${RESET}\n"
  exit 1
fi
