#!/usr/bin/python3

import argparse
import libarchive
import os
import shutil
import subprocess
import sys
from pathlib import Path

MTOOLS_HDIMAGE_FILESYSTEM_OFFSET = '@@32384'

def install_opendos_from_rpm(source, drive_root):
    TMP_DIR = os.path.join('/tmp', os.path.basename(sys.argv[0]) + '-' + os.environ['USER'] + '-' + str(os.getpid()))
    os.makedirs(TMP_DIR, exist_ok=True)
    os.makedirs(drive_root, exist_ok=True)

    archive_file = list(Path(source).glob('opendos-hdimage*.rpm'))[0]
    with libarchive.file_reader(str(archive_file)) as archive:
        for entry in archive:
            if entry.pathname == 'hdimage.od':
                    with open(os.path.join(TMP_DIR, 'hdimage.od'), 'wb') as output_file:
                        for block in entry.get_blocks():
                            output_file.write(block)
                        output_file.close()
    subprocess.run(['mcopy', '-sn', '-i', os.path.join(TMP_DIR, 'hdimage.od') + MTOOLS_HDIMAGE_FILESYSTEM_OFFSET, '::*', drive_root], env={"PATH": os.environ['PATH'], "MTOOLS_LOWER_CASE": '1'})
    shutil.rmtree(TMP_DIR)

def verify_tool(executable, package):
    (status, output) = subprocess.getstatusoutput('which ' + executable)
    if status != 0:
        print('Please install ' + package + ' and make sure that ' + executable + ' is on your PATH.')
        sys.exit(1)

def verify_system():
    verify_tool('mcopy', 'mtools')

verify_system()

parser = argparse.ArgumentParser(description="""OpenDOS installation scipt.
The result resembles an OpenDOS environment as was shipped along DOSEMU 1 on Caldera OpenLinux.""")
parser.add_argument("source", type=str, help="""source directory containing DOS installation files;
Only RPMs are supported (as were shipped by Caldera OpenLinux).""")
parser.add_argument("destination", type=str, help="destination root directory")

args = parser.parse_args()

# system installation
info = subprocess.run(['dosemu', '-info'], stdout=subprocess.PIPE).stdout.decode(sys.stdout.encoding).splitlines()[0]
cmddir = os.path.join(info[info.find(': ') + 2:], 'share', 'dosemu', 'commands', 'c')
if list(Path(args.source).glob('opendos-hdimage*.rpm')):
    install_opendos_from_rpm(args.source, args.destination)
    shutil.copy(os.path.join(cmddir, 'odconfig.sys'), args.destination)
    shutil.copy(os.path.join(cmddir, 'odautoem.bat'), args.destination)
    tmp_name = args.destination + '/tmp'
    if not Path(tmp_name).exists():
        os.mkdir(tmp_name)
    sys.exit(0)

print('No DOS installation files were found.')
print('Run loaddosinstall as root to download a version of DOS.')
sys.exit(1)
