#!/usr/bin/python3

import argparse
import os
import shutil
import sys
import time
import zipfile
import zlib
from pathlib import Path

def extract_zipfile_entry(archive, zipinfo, output_filename):
    if Path(output_filename).exists():
        with open(output_filename, 'rb') as existing_file:
            existing_file_crc32 = zlib.crc32(existing_file.read())
            existing_file.close()
        if existing_file_crc32 == zipinfo.CRC:
            print('File with equal content ' + output_filename + ' already exists, skipping...')
            return
        else:
            print('Existing file with different content found: ' + output_filename + """
                  Likely another DOS version is installed already. Remove the
                  existing file and rerun this script to proceed.""")
            sys.exit(1)
    with open(output_filename, 'wb') as output_file:
        output_file.write(archive.read(zipinfo.filename))
        output_file.close()
    os.utime(output_filename, (time.time(), time.mktime(zipinfo.date_time + (0, 0, -1))))

def extract_archive(filename, drive_root):
    archive = zipfile.ZipFile(filename)
    for entry in archive.infolist():
        filename = entry.filename.lower()
        output_filename = os.path.join(drive_root, filename)
        extract_zipfile_entry(archive, entry, output_filename)

parser = argparse.ArgumentParser(description="""SvarDOS installation script.""")
parser.add_argument("source", type=str, help="""source directory containing SvarDOS installation files;""")
parser.add_argument("destination", type=str, help="""destination root directory""")

args = parser.parse_args()

# system installation
arch_name = 'svardos-20220816-dosemu.zip'
if list(Path(args.source).glob(arch_name)):
    print('Extracting ' + args.source + '/' + arch_name + ' to ' + args.destination)
    os.makedirs(args.destination, exist_ok=True)
    extract_archive(args.source + '/' + arch_name, args.destination)
    tmp_name = args.destination + '/tmp'
    if not Path(tmp_name).exists():
        os.mkdir(tmp_name)
    sys.exit(0)

print('No SvarDOS installation image found.')
sys.exit(1)
