#!/usr/bin/env python3

################################################################################
# Title:        Bldhelper.py
# Description:  Script to build PeppermintOS ISO image
# Author:       PeppermintOS Team <peppermintosteam@proton.me>
# Date:         May 10, 2023
# License:      GPL-3.0-or-later
################################################################################

import os
import shutil
import datetime

# Set environment variables
PREFIX = "Pepserver"
SUFFIX = "amd64"
BUILD = "Deb"
TODAY = datetime.datetime.utcnow().strftime("%Y-%m-%d")
FileName = f"{PREFIX}-{SUFFIX}"
LOCATION = "/var/www/html/nightly/PepOSServer/" + BUILD
LogDir = "/var/log/Live-Build"
WorkingDir = "/home/pepadmin/PepOSServer/bookworm"

# Execute the ISO building script
os.chdir(WorkingDir)
os.system("python3 pepbld.py")

# Move and rename the ISO file
os.chdir("fusato")
iso_files = [f for f in os.listdir() if f.endswith(".iso")]
if len(iso_files) > 0:
    shutil.move(iso_files[0], f"{FileName}-{TODAY}.iso")

# Create the checksum file for the ISO
iso_files = [f for f in os.listdir() if f.endswith(".iso")]
if len(iso_files) > 0:
    iso_file = iso_files[0]
    checksum_file = f"{FileName}-{TODAY}-sha512.checksum"
    os.system(f"sha512sum {iso_file} > {checksum_file}")

# Remove old ISO and checksum files from the desired location
os.chdir(LOCATION)
old_files = [f for f in os.listdir() if f.startswith(FileName)]
for old_file in old_files:
    os.remove(old_file)

# Move the ISO and checksum files to the desired location
os.chdir(os.path.join(WorkingDir, "fusato"))
if os.path.exists(LOCATION):
    shutil.move(f"{FileName}-{TODAY}.iso", LOCATION)
    shutil.move(f"{FileName}-{TODAY}-sha512.checksum", LOCATION)
else:
    print(f"Location {LOCATION} does not exist")

# Move the log file to the log directory (if it exists)
log_file = f"/tmp/{PREFIX}{SUFFIX}.out"
if os.path.exists(log_file):
    shutil.move(log_file, f"{LogDir}/{PREFIX}-{SUFFIX}-{BUILD}.log")

# Clean the build folder 
os.system("lb clean")

# Remove the "fusato" directory and its contents
os.chdir(WorkingDir)
shutil.rmtree("fusato")

