
import spawn from '../spawn'
import sf from '../sf'
import sudo from '../sudo'

import common from './common'

import tmp from 'tmp'

// note: itch-player's password is not a secret, as everything itch-player
// owns should be accessible by other users as well (but not the other
// way around)
const USER = 'itch-player'
const PASSWORD = 'salt'

export async function check () {
  const errors = []
  const needs = []

  const userCheck = await spawn.exec({command: 'net', args: ['user', USER]})
  if (userCheck.code !== 0) {
    needs.push({
      type: 'user',
      err: userCheck.err,
      code: userCheck.code
    })
  }

  return {errors, needs}
}

export async function install (opts, needs) {
  return await common.tendToNeeds(opts, needs, {
    user: async () => {
      const lines = []
      lines.push(`net user ${USER} ${PASSWORD} /add`)
      // if we don't do this, it shows as a login user
      lines.push(`net localgroup Users ${USER} /delete`)
      await adminRunScript(lines)
    }
  })
}

export async function uninstall (opts) {
  return {errors: []}
}

async function adminRunScript (lines) {
  const contents = lines.join('\r\n')
  const tmpObj = tmp.fileSync({postfix: '.bat'})
  sf.writeFile(tmpObj.name, contents)

  console.log(`running batch script:\r\n${contents}`)

  let out = ''
  let e

  try {
    await sudo.execAsync(`cmd.exe /c "${tmpObj.name}"`, {
      name: 'itch sandbox setup',
      on: (ps) => {
        ps.stdout.on('data', (data) => { out += data })
      }
    })
  } catch (err) { e = err }

  if (process.env.KEEP_MESS_AROUND === '1') {
    console.log(`keeping temp batch script at ${tmpObj.name}`)
  } else {
    tmpObj.removeCallback()
  }

  if (e) { throw e }

  return {out}
}

export default {check, install, uninstall}

@@ -49,35 +49,8 @@
 /sf'
-%0Aimport sudo from '../sudo'
 %0A%0Aim
@@ -439,33 +439,70 @@
 d: '
-net', args: %5B'user', USER
+elevate.exe', args: %5B'--runas', USER, PASSWORD, 'echo', 'good'
 %5D%7D)%0A
@@ -803,16 +803,64 @@
 es = %5B%5D%0A
+      // in case the user was incorrectly setup%0A
       li
@@ -1358,49 +1358,27 @@
 %0A%0A  
-let out = ''%0A  let e%0A%0A  try %7B%0A   
+const res =
  await s
 udo.
@@ -1377,207 +1377,93 @@
 it s
-udo
+pawn
 .exec
-Async(%60cmd.exe /c %22$%7BtmpObj.name%7D%22%60, %7B%0A      name: 'itch sandbox setup',%0A      on: (ps) =%3E %7B%0A        ps.stdout.on('data', (data) =%3E %7B out += data %7D)%0A      %7D%0A    %7D)%0A  %7D catch (err) %7B e = err %7D
+(%7B%0A    command: 'elevate.exe',%0A    args: %5B'cmd.exe', '/c', tmpObj.name%5D%0A  %7D)
 %0A%0A  
@@ -1623,20 +1623,134 @@
 if (
-e) %7B throw e
+res.code !== 0) %7B%0A    throw new Error(%60adminRunScript failed with code $%7Bres.code%7D. out = $%7Bres.out%7D%5Cn, err = $%7Bres.err%7D%5Cn%60)%0A 
  %7D%0A%0A
@@ -1762,16 +1762,25 @@
 urn %7Bout
+: res.out
 %7D%0A%7D%0A%0Aexp

Use our own elevate