Create programmatically a ACL logic
Yes, the API is definitely the correct approach.  Writing via SQL may work for now, but isn't guaranteed to in the future.

For the first item (creating the Joomla) user, I can't offer help, since that's not CiviCRM.  There are plenty of pages that indicate how to create a Joomla user programmatically.

Don't forget about the API Explorer (Support menu » Developer » API Explorer) to help with determining how to implement your solution.

Also consider the CSV API Import tool, which may provide a no-coding (or low-coding alternative.

Create the contact (step 2) with the "Contact" API.
Connect it to the group (step 3) with the "GroupContact" API.  Use the "Group" API if the groups don't currently exist.

Step 4 needs the OptionValue API to create the role (set "Option Group ID" to acl_role).  Use the Acl and AclRole API to set the rest.