#Requires -Version 3.0
#Requires -RunAsAdministrator
<#
.SYNOPSIS
    Creates a scheduled task to run the user activity tracking script at logon.
.DESCRIPTION
    This script creates a Windows Task Scheduler task that launches the
    run_hidden.vbs (which in turn runs report.ps1) script whenever a user 
    logs into the system. It must be run with administrative privileges.
.NOTES
    File Name  : schedule_task.ps1
    Author     : IT Department
    Version    : 1.5 (Modified to schedule run_hidden.vbs)
.EXAMPLE
    .\schedule_task.ps1 -ScriptPath "C:\Path\To\report.ps1" 
    (Ensure run_hidden.vbs is in the same directory as report.ps1)
    
    # To avoid security warnings, you can unblock the files first:
    # Unblock-File -Path schedule_task.ps1
    # Unblock-File -Path report.ps1
    # Unblock-File -Path run_hidden.vbs
#>

param (
    [Parameter(Mandatory=$true)]
    [string]$ScriptPath # Path to the main report.ps1 script
)

# Begin by unblocking the files to prevent security warnings
Write-Host "Attempting to unblock script files..."
$ReportScriptDir = Split-Path -Path $ScriptPath -Parent
$VbsPath = Join-Path -Path $ReportScriptDir -ChildPath "run_hidden.vbs"

try {
    Unblock-File -Path $ScriptPath -ErrorAction SilentlyContinue
    if (Test-Path $VbsPath) {
        Unblock-File -Path $VbsPath -ErrorAction SilentlyContinue
    }
    Unblock-File -Path $MyInvocation.MyCommand.Path -ErrorAction SilentlyContinue
    Write-Host "Files unblocked successfully or unblock attempted."
} catch {
    Write-Host "Unable to unblock files. If you see security warnings, you may need to run Unblock-File manually."
}

# Verify the main PowerShell script exists
if (-not (Test-Path $ScriptPath)) {
    Write-Error "Main PowerShell script (report.ps1) not found at path: $ScriptPath"
    exit 1
}

# Make sure the path to report.ps1 is absolute
$AbsoluteReportScriptPath = (Resolve-Path $ScriptPath).Path
$ResolvedScriptDir = Split-Path -Parent $AbsoluteReportScriptPath
$AbsoluteVbsLauncherPath = Join-Path $ResolvedScriptDir "run_hidden.vbs"

if (-not (Test-Path $AbsoluteVbsLauncherPath)) {
    Write-Error "VBS Launcher (run_hidden.vbs) not found in script directory: $ResolvedScriptDir (expected alongside $AbsoluteReportScriptPath)"
    exit 1
}

# Task settings
$taskName = "UserActivityTracking"
$taskDescription = "Monitors user activity and reports to central server via VBS launcher"

# Check if the task already exists and remove it
$existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($existingTask) {
    Write-Host "Task '$taskName' already exists. Removing it..."
    schtasks /Delete /TN $taskName /F
}

# The command to be executed by the task is the path to the VBS file
$TaskExecutableAndArgs = $AbsoluteVbsLauncherPath

try {
    # Use schtasks.exe command to create the task
    # /TR now points directly to the .vbs file, which is simpler for schtasks quoting
    # Ensure task name and executable path are quoted if they could contain spaces
    $createCmd = "schtasks /Create /TN `"$taskName`" /TR `"$TaskExecutableAndArgs`" /SC ONLOGON /F /RU INTERACTIVE /IT /DELAY `"0000:30`"" 
    Write-Host "Creating scheduled task with command: $createCmd"
    Invoke-Expression $createCmd
    
    # Verify task was created
    $taskExists = schtasks /Query /TN $taskName 2>$null
    if ($LASTEXITCODE -eq 0) {
        Write-Host "Task '$taskName' has been created successfully."
        Write-Host "The activity tracking launcher (run_hidden.vbs) will now run at each user logon."
        Write-Host "VBS Launcher path: $AbsoluteVbsLauncherPath"
    } else {
        Write-Error "Task creation verification failed. The task may not have been created properly."
    }
} catch {
    Write-Error "Failed to create scheduled task: $_"
    exit 1
}

# Copy config.env next to report.ps1 file if it exists in the source deployment directory
$configEnvSource = Join-Path (Split-Path $MyInvocation.MyCommand.Path -Parent) "config.env"
$configEnvDest = Join-Path $ResolvedScriptDir "config.env"

if (Test-Path $configEnvSource) {
    if ((Resolve-Path $configEnvSource).Path -ne (Resolve-Path $configEnvDest -ErrorAction SilentlyContinue).Path) {
        try {
            Copy-Item -Path $configEnvSource -Destination $configEnvDest -Force
            Write-Host "Copied config.env to script directory: $configEnvDest"
        } catch {
            Write-Warning "Failed to copy config.env to script directory: $_"
        }
    } else {
        Write-Host "Config.env is already in the script directory."
    }
} else {
    Write-Warning "config.env not found in the directory of schedule_task.ps1. Ensure it's manually placed next to report.ps1."
}

Write-Host "`nIMPORTANT: To manually verify the task was created correctly, open Task Scheduler`n(taskschd.msc) and check for the 'UserActivityTracking' task." 