#!/bin/sh
#
# Copyright (c) 2003-2004 Silicon Graphics, Inc.  All Rights Reserved.
# 
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
# 
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# Post installation/upgrade script for PCP
#

prog=`basename $0`
status=1
trap "exit \$status" 0 1 2 15

echo "$prog: PCP for macOS Install"

echo "$prog: Writing install log to /var/log/pcp_inst.log" | tee /var/log/pcp_inst.log

if [ ! -d $2 ]
then
    echo "$prog: Unable to open directory of new files ($2)" | tee -a /var/log/pcp_inst.log
    exit
fi

if ./install-pcp -i -l /var/log/pcp_inst.log idb
then
    :
else
    echo "$prog: Install Failed" | tee -a /var/log/pcp_inst.log
    exit
fi

if [ -f /etc/pcp.conf ]
then
    # for all the configuration files we know about, salt away file
    # with a .orig suffix for a subsequent upgrade
    #
    . /etc/pcp.conf
    for conf in \
	$PCP_PMCDCONF_PATH $PCP_PMCDOPTIONS_PATH $PCP_PMCDRCLOCAL_PATH \
	$PCP_PMIECONTROL_PATH $PCP_PMLOGGERCONTROL_PATH \
	$PCP_PMPROXYOPTIONS_PATH $PCP_PMWEBDOPTIONS_PATH
    do
	[ -f $conf ] && cp $conf $conf.orig
    done
fi

# create the user/group account that PCP daemons will use
#
userid=432
groupid=432

if ! dscl . -list /Groups | grep -q '^pcp$' 
then
    dscl . -create /Groups/pcp
    dscl . -create /Groups/pcp PrimaryGroupID $groupid
    dscl . -create /Groups/pcp Password \*
fi

if ! dscl . -list /Users | grep -q '^pcp$' 
then
    dscl . -create /Users/pcp
    dscl . -create /Users/pcp UniqueID $userid
    dscl . -create /Users/pcp UserShell /usr/bin/false
    dscl . -create /Users/pcp RealName 'Performance Co-Pilot'
    dscl . -create /Users/pcp NFSHomeDirectory /var/lib/pcp
    dscl . -create /Users/pcp PrimaryGroupID $groupid
    dscl . -create /Users/pcp Password \*
    dscl . append /Groups/pcp GroupMembership pcp
fi

chown -R pcp:pcp /var/log/pcp 2>/dev/null
chown -R pcp:pcp /var/lib/pcp/config 2>/dev/null

# https://github.com/performancecopilot/pcp/issues/20
defaults write io.pcp.pmtime NSAppSleepDisabled -bool YES

# cull any old files or directories that used to be in the distribution
# but that have gone away or moved somewhere else
#
for file in /var/lib/pcp/config/pmieconf/pcp/pmda_status
do
    [ -f "$file" ] && rm -f "$file"
done
for dir in /var/lib/pcp/config/pmieconf/pcp
do
    [ -d "$dir" ] && rm -rf "$dir"
done

# Ensure pmcd is loaded...
launchctl bootstrap system /Library/LaunchDaemons/io.pcp.pmcd.plist
# ...and then started by launchctl - it would get picked up by a reboot, but this leaves pmcd running after install
launchctl kickstart -p -k system/io.pcp.pmcd

# Install optional PMDAs directly (not via .NeedInstall).
# On Linux, rc_pmcd's _pmda_setup() processes .NeedInstall markers on
# startup. On macOS, launchd's kickstart bypasses rc_pmcd, so we run
# the Install scripts directly after pmcd is up.
#
if [ -f /etc/pcp.conf ]; then
    . /etc/pcp.conf
    # Give pmcd a moment to be ready for PMDA registrations
    sleep 2
    for PMDA in openmetrics opentelemetry ; do
        if ! grep -q "$PMDA/pmda$PMDA" "$PCP_PMCDCONF_PATH" 2>/dev/null; then
            if test -d "$PCP_PMDAS_DIR/$PMDA" -a -x "$PCP_PMDAS_DIR/$PMDA/Install"; then
                echo "$prog: Installing $PMDA PMDA" | tee -a /var/log/pcp_inst.log
                cd "$PCP_PMDAS_DIR/$PMDA" && ./Install </dev/null >>/var/log/pcp_inst.log 2>&1
                echo "$prog: $PMDA PMDA install exit status: $?" | tee -a /var/log/pcp_inst.log
            else
                echo "$prog: $PMDA PMDA not bundled (missing $PCP_PMDAS_DIR/$PMDA)" | tee -a /var/log/pcp_inst.log
            fi
        else
            echo "$prog: $PMDA PMDA already configured" | tee -a /var/log/pcp_inst.log
        fi
    done
fi

# Ensure pmproxy is loaded...
echo "$prog: Starting pmproxy service" | tee -a /var/log/pcp_inst.log
launchctl bootstrap system /Library/LaunchDaemons/io.pcp.pmproxy.plist
# ...and then started by launchctl
launchctl kickstart -p -k system/io.pcp.pmproxy

# Load periodic maintenance tasks (launchd scheduled jobs)
# These are the macOS equivalent of systemd timers / cron on Linux.
# They handle health checks and log rotation for pmlogger and pmie.
echo "$prog: Loading periodic maintenance tasks" | tee -a /var/log/pcp_inst.log
for plist in \
    io.pcp.pmlogger_check \
    io.pcp.pmlogger_daily \
    io.pcp.pmlogger_farm_check \
    io.pcp.pmie_check \
    io.pcp.pmie_daily \
    io.pcp.pmie_farm_check
do
    launchctl bootstrap system /Library/LaunchDaemons/${plist}.plist
    echo "$prog: Loaded ${plist}" >> /var/log/pcp_inst.log
done

# Debug: Check for pmproxy log files for troubleshooting
echo "$prog: Checking for pmproxy logs" | tee -a /var/log/pcp_inst.log
if [ -d /var/log/pcp/pmproxy ]; then
    echo "$prog: pmproxy log directory exists" | tee -a /var/log/pcp_inst.log
    for logfile in /var/log/pcp/pmproxy/*.log; do
        if [ -f "$logfile" ]; then
            echo "$prog: Found log file: $logfile" | tee -a /var/log/pcp_inst.log
            echo "$prog: Contents of $logfile:" | tee -a /var/log/pcp_inst.log
            cat "$logfile" | tee -a /var/log/pcp_inst.log
        fi
    done
else
    echo "$prog: pmproxy log directory does not exist yet" | tee -a /var/log/pcp_inst.log
fi

status=0
