#!/usr/bin/python3
# Author: Alon Swartz <alon@turnkeylinux.org>

import os
import sys

if '_TURNKEY_INIT' in os.environ:
    sys.exit(0)

from os.path import join
import subprocess

import ec2metadata

DIR = '/var/lib/inithooks/ec2metadata'


def main():
    userdata = ec2metadata.get('user-data')
    os.makedirs(DIR, exist_ok=True)

    if userdata and userdata.decode().startswith("#!"):
        os.makedirs(DIR, exist_ok=True)
        script = join(DIR, 'user-data.sh')
        with open(script, "wb") as fob:
            fob.write(userdata)
        os.chmod(script, 0o750)
        ec2meta = subprocess.run([script], capture_output=True, text=True)
        if ec2meta.returncode == 0:
            os.remove(script)
            print("# executed ec2 user-data script")
        else:
            line = f"# ERROR: executing ec2 user-data script failed ({script})"
            log = '/var/log/userdata.log'
            with open(log, 'w') as fob:
                print(line, f'\n - see {log} for details.')
                fob.write(line+'\n\n')
                fob.writelines(ec2meta.stderr)
            sys.exit(1)


if __name__ == "__main__":
    main()
