#!/bin/bash

# Build script for EIS User Activity Recording Plugin (RecordSupport) for Porteus
# Version 2026-07-05

# 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.

if [ "$(whoami)" != "root" ]; then
    echo -e "\nYou must be root to run this script.\n"
    exit 1
fi

echo -e "\n${BOLD}Before building, you need to download the plugin archive manually.${RESET}"
echo -e "1) Open the following URL in your browser:"
echo -e "   ${CYAN}https://zakupki.gov.ru/epz/main/public/document/view.html?searchString=&sectionId=1767&strictEqual=false${RESET}"
echo -e "2) Find and download the file named ${CYAN}Linux_x64.tar.gz${RESET}."
echo -e "3) Place the downloaded archive in the same directory as this script:"
echo -e "   ${CYAN}$(pwd)${RESET}\n"
read -p "Press Enter after you have placed the archive here, or Ctrl+C to cancel..." -r

PRGNAM="recordsupport"
BUILD=${BUILD:-1}
ARCH="x86_64"

BOLD=${BOLD:-"\e[1m"}
CYAN=${CYAN:-"\e[96m"}
GREEN=${GREEN:-"\e[92m"}
RED=${RED:-"\e[31m"}
YELLOW=${YELLOW:-"\e[93m"}
RESET=${RESET:-"\e[0m"}

CWD=$(pwd)
TMPDIR=/tmp/portch
PKG=$TMPDIR/package-$PRGNAM
PKGINFO=$PKG/var/lib/pkgtools/packages
OUTPUT=${OUTPUT:-/tmp}

cleanup() {
    [ -d "$TMPDIR" ] && rm -rf "$TMPDIR"
    [ -d "$PKG" ] && rm -rf "$PKG"
    exit
}

if [ -f "Linux_x64.tar.gz" ]; then
    echo -e "${CYAN}Found Linux_x64.tar.gz, extracting...${RESET}"
    mkdir -p "$TMPDIR/outer"
    tar -xzf "Linux_x64.tar.gz" -C "$TMPDIR/outer" || {
        echo -e "${RED}Failed to extract Linux_x64.tar.gz${RESET}"
        cleanup
    }
    INSTDIR=$(find "$TMPDIR/outer" -name "data.tar.gz" -printf "%h\n" 2>/dev/null | head -1)
    if [ -z "$INSTDIR" ]; then
        echo -e "${RED}Cannot locate data.tar.gz inside Linux_x64.tar.gz${RESET}"
        cleanup
    fi
    cd "$INSTDIR" || cleanup
    echo "Found installer files in: $INSTDIR"
else
    echo -e "${RED}Linux_x64.tar.gz not found in the current directory.${RESET}"
    echo "Please download it manually and place it here, then run the script again."
    cleanup
fi

extract_and_locate() {
    local archive="$1"
    local dest="$TMPDIR/data_extracted"
    mkdir -p "$dest"
    echo -e "${CYAN}Extracting $archive...${RESET}"
    tar -xzf "$archive" -C "$dest" || {
        echo -e "${RED}Failed to extract $archive${RESET}"
        cleanup
    }

    echo "Locating plugin components..."
    local found=$(find "$dest" -name "RecordSupportSystem" -type f 2>/dev/null | head -1)
    if [ -z "$found" ]; then
        echo -e "${RED}Cannot find RecordSupportSystem inside the archive.${RESET}"
        cleanup
    fi

    local record_dir=$(dirname "$found")
    COMPONENTS_ROOT=$(dirname "$record_dir")

    for dir in RecordSupport ffmpeg Properties cert scripts; do
        if [ ! -d "$COMPONENTS_ROOT/$dir" ]; then
            echo -e "${RED}Missing directory: $dir${RESET}"
            cleanup
        fi
    done

    echo "All components found at: $COMPONENTS_ROOT"
    export COMPONENTS_ROOT
}

mkdir -p "$TMPDIR"

if [ -f "data.tar.gz" ]; then
    echo "Local data.tar.gz found."
    extract_and_locate "data.tar.gz"
elif [ -d "data/RecordSupport" ]; then
    echo "Already extracted 'data' directory found."
    COMPONENTS_ROOT="$PWD/data"
else
    echo -e "${RED}No data.tar.gz or data/ directory found in the installer.${RESET}"
    cleanup
fi

read -p "Enter version (e.g., 16.1.1.141): " VERSION
[ -z "$VERSION" ] && { echo "Version cannot be empty."; cleanup; }

echo -e "Using version: ${GREEN}${VERSION}${RESET}"

INSTALLED_VER=""
if ls /var/lib/pkgtools/packages/${PRGNAM}-* 1>/dev/null 2>&1; then
    INSTALLED_VER=$(basename /var/lib/pkgtools/packages/${PRGNAM}-* | cut -d'-' -f2)
fi
if [ "$INSTALLED_VER" = "$VERSION" ]; then
    echo -e "Latest version ${GREEN}$VERSION${RESET} already installed."
    sleep 3
    cleanup
fi

[ -n "$INSTALLED_VER" ] && echo -e "Upgrading from ${RED}$INSTALLED_VER${RESET} to ${GREEN}$VERSION${RESET}"
read -p "$(echo -e "Build $PRGNAM ${GREEN}$VERSION${RESET} module? [y/n] ")" -n 1 -r -s && echo
[[ ! $REPLY =~ ^[Yy]$ ]] && cleanup

rm -rf "$PKG"
mkdir -p "$PKG/opt/$PRGNAM" \
         "$PKG/etc/xdg/autostart" \
         "$PKG/usr/share/applications" \
         "$PKG/usr/bin" \
         "$PKGINFO"

echo "Copying plugin files..."
cp -a "$COMPONENTS_ROOT/RecordSupport"/* "$PKG/opt/$PRGNAM/"
cp -a "$COMPONENTS_ROOT/ffmpeg"        "$PKG/opt/$PRGNAM/"
cp -a "$COMPONENTS_ROOT/Properties"    "$PKG/opt/$PRGNAM/"
cp -a "$COMPONENTS_ROOT/cert"          "$PKG/opt/$PRGNAM/"
cp -a "$COMPONENTS_ROOT/scripts"       "$PKG/opt/$PRGNAM/"

chmod +x "$PKG/opt/$PRGNAM/RecordSupportSystem" \
         "$PKG/opt/$PRGNAM/ffmpeg/ffmpeg" \
         "$PKG/opt/$PRGNAM/ffmpeg/runffmpeg" \
         "$PKG/opt/$PRGNAM/scripts/"* \
         "$PKG/opt/$PRGNAM/cert/certutil"

find "$PKG" -exec chown root:root {} \;
find "$PKG" \
    \( -perm 777 -o -perm 775 -o -perm 750 -o -perm 711 -o -perm 555 -o -perm 511 \) -exec chmod 755 {} \; \
    -o \
    \( -perm 666 -o -perm 664 -o -perm 640 -o -perm 600 -o -perm 444 -o -perm 440 -o -perm 400 \) -exec chmod 644 {} \;

ln -sf /opt/$PRGNAM/RecordSupportSystem "$PKG/usr/bin/$PRGNAM"

cat > "$PKG/usr/share/applications/$PRGNAM.desktop" << EOF
[Desktop Entry]
Type=Application
Name=RecordSupport EIS Plugin
Comment=User activity recording for EIS (zakupki.gov.ru)
Exec=/opt/$PRGNAM/RecordSupportSystem
Terminal=false
NoDisplay=true
Categories=Utility;
EOF

ln -sf /usr/share/applications/$PRGNAM.desktop "$PKG/etc/xdg/autostart/$PRGNAM.desktop"

echo "Stripping ELF executables..."
find "$PKG" -type f -print0 | xargs -0 file | grep -E "ELF.*(executable|shared object)" | cut -f 1 -d : | xargs strip --strip-unneeded 2>/dev/null || true

CERT_FILE="$PKG/opt/$PRGNAM/cert/rootCA.pem"
NSSDB="/home/guest/.local/share/pki/nssdb"
CERTUTIL_BIN=""

if [ -x "$PKG/opt/$PRGNAM/cert/certutil" ]; then
    CERTUTIL_BIN="$PKG/opt/$PRGNAM/cert/certutil"
elif command -v certutil &>/dev/null; then
    CERTUTIL_BIN=$(which certutil)
fi

if [ -n "$CERTUTIL_BIN" ] && [ -f "$CERT_FILE" ]; then
    echo "Attempting to import root certificate for RecordSupport..."
    su - guest -c "mkdir -p \"$NSSDB\" && if [ ! -f \"$NSSDB/cert9.db\" ]; then $CERTUTIL_BIN -N -d sql:\"$NSSDB\" --empty-password; fi" 2>/dev/null
    su - guest -c "$CERTUTIL_BIN -d sql:\"$NSSDB\" -A -t 'C,,' -n 'RecordSupport Root CA' -i \"$CERT_FILE\"" 2>/dev/null && echo "Certificate imported successfully." || echo "Warning: automatic import failed, you'll need to import manually."
fi

echo "PACKAGE NAME: $PRGNAM-$VERSION-$ARCH" > "$PKGINFO/$PRGNAM-$VERSION-$ARCH"
cat >> "$PKGINFO/$PRGNAM-$VERSION-$ARCH" << EOM
PACKAGE DESCRIPTION:
recordsupport: RecordSupport – user activity recording plugin for the Unified
recordsupport: Information System in procurement (EIS).
recordsupport:
recordsupport: Records user actions (screenshots, input events) while working
recordsupport: on zakupki.gov.ru.
recordsupport:
recordsupport: Version: $VERSION
recordsupport:
FILE LIST:
EOM

cd "$PKG" || exit
find * | grep -v var >> "$PKGINFO/$PRGNAM-$VERSION-$ARCH"

echo -e "\n${CYAN}Building module $PRGNAM-$VERSION-$ARCH-$BUILD.xzm${RESET}"
dir2xzm "$PKG" "$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm"

if [ -f "$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm" ]; then
    echo -e "\n${BOLD}Module successfully created: ${GREEN}$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm${RESET}"
    echo -e "${BOLD}Copy the module to your Porteus modules directory $PORTDIR/modules and activate it.${RESET}"
    echo -e "${BOLD}After activation:"
    echo -e "  1. Reboot or re-login for autostart."
    echo -e "  2. Import the root certificate to trust the local service (if not done automatically):"
    echo -e "     ${BOLD}su - guest -c 'certutil -d sql:/home/guest/.local/share/pki/nssdb -A -t \"C,,\" -n \"RecordSupport Root CA\" -i /opt/recordsupport/cert/rootCA.pem'${RESET}"
    echo -e "  3. Restart Chromium-Gost completely.${RESET}"
else
    echo -e "\n${RED}Error: module was not built.${RESET}"
fi

cleanup
